JS原型和原型链

一  综上 我们可以总结:每个构造函数生成实例的时候 会自带一个constructor属性 指向该构造函数 

所以        实例.constructor == 构造函数

var arr = new Array();

arr.constructor === Array; //true

arr instanceof Array; //true
 

二 同时 Javascript规定,每一个构造函数都有一个prototype属性,指向另一个对象。这个对象的所有属性和方法,都会被构造函数的实例继承。

  1.  
    function Cat(name){
  2.  
    this.name = name;
  3.  
    }
  4.  
    Cat.sex = '女';
  5.  
    Cat.prototype.age = '12';
  6.  
    var cat = new Cat('大黄');
  7.  
    alert(cat.age);//12
  8.  
    alert(cat.sex);//undefine 也就是说明实例只能继承构造函数原型上的属性和方法
alert(cat.hasOwnProperty("name"));// hasOwnProperty判断是自己本身的属性还是继承的 alert(cat.hasOwnProperty("age"));
三  JS在创建对象(不论是普通对象还是函数对象)的时候,都有一个叫做__proto__的内置属性,用于指向创建它的函数对象的原型对象prototype。

以上例子为例:

alert(cat.__proto__===Cat.prototype);
同样,Cat.prototype对象也有__proto__属性,它指向创建它的函数对象(Object)的prototype
alert(Cat.prototype.__proto__=== Object.prototype);

继续,Object.prototype对象也有__proto__属性,但它比较特殊,为null

alert(Object.prototype.__proto__);//null 
我们把这个有__proto__串起来的直到Object.prototype.__proto__为null的链叫做原型链。

所以 

var Person = function () { }; Person.prototype.Say = function () { alert("Person say"); } Person.prototype.Salary = 50000; var Programmer = function () { }; Programmer.prototype = new Person(); Programmer.prototype.WriteCode = function () { alert("programmer writes code"); }; Programmer.prototype.Salary = 500; var p = new Programmer();
/*
*在执行p.Say()时,先通过p._proto_找到Programmer.prototype
* 然而并没有Say方法,继续沿着Programmer.prototype._proto_ 找到Person.prototype,ok 此对象下有Say方法 执行之
*/

p.Say();
p.WriteCode(); //同理 在向上找到Programmer.prototype时 找到WriteCode方法 执行之

所以
var animal = function(){}; var dog = function(){}; dog.price = 300; dog.prototype.cry = function () { alert("++++"); } animal.price = 2000; dog.prototype = new animal(); var tidy = new dog(); console.log(dog.cry) //undefined console.log(tidy.price) // undefined
原文地址:https://www.cnblogs.com/web-chuanfa/p/9395025.html