JS原型和原型链

原型和原型链在JS中是比较复杂的一块,接下里开始我们基础知识的学习

  1.prototype和__proto__的区别:prototype原型对象只有函数才拥有的属性,__proto__是所有对象都拥有的属性。

var a = {};console.log(a.prototype); //undefinedconsole.log(a.__proto__); //Object {}var b = function(){}console.log(b.prototype); //b {}console.log(b.__proto__); //function() {}

  2.constructor:默认情况下,所有的原型对象都会自动获取一个constructor属性,这个属性指向prototype属性所在的那个函数

function Person(){this.name=name;}var child = new Person()child.constructor = Person//true
Person.prototype.constructor === Person//true

   3.__proto__:任何一个JS对象都包括这个属性,他是用于指向创建他的构造函数的原型对象

child.__proto__ === Person.prototype // true

   4.什么是原型链:由于__proto__是所有对象都有的属性,js里万物皆对象,所以会形成一条__proto__链条,递归访问会到头,最后会到null

var A = function(){};var a = new A();console.log(a.__proto__); //A {}(即构造器function A 的原型对象)console.log(a.__proto__.__proto__); //Object {}(即构造器function Object 的原型对象)console.log(a.__proto__.__proto__.__proto__); //null

 

 

相关文章