关于 prototype 与__proto__
- js中全部的函数都有一个 prototype 属性,该属性引用了一个对象,即原型对象,也简称原型
- js对象有一个__proto__属性,指向它的构造函数的prototype属性
- 对象.__proto__===函数.prototype;
var a = new A; //a 类型:对象 //A 类型:函数 var Object = new Function(); //var 对象 = new 函数; Object.__proto__ === Function.prototype; //对象.__proto__ === 函数.prototype; Function.__proto__ === Function.prototype; //由于 Function 也是 Object
//建立构造函数 function demo(name){ this.name= name; } demo.prototype = { alert(){ alert(this.name); } } //建立实例 var a = new demo("ming"); a.print = function(){ console.log(this.name); console.log(this); //Person对象 } a.print(); //控制台内容以下
a.alert(); //弹出ming
print()方法是a实例自己具备的方法,因此 a.print() 打印 ming数组
alert()不属于a实例的方法,属于构造函数的方法,a.alert() 也会打印 ming,由于实例继承构造函数的方法函数
实例a的隐式原型指向它构造函数的显式原型,指向的意思是恒等于this
a.__proto__ === demo.prototype
Function.prototype.a = "a"; Object.prototype.b = "b"; function Person(){} console.log(Person); //function Person() let p = new Person(); console.log(p); //Person {} 对象 console.log(p.a); //undefined console.log(p.b); //b
因为 p 是 Person() 的实例,是一个 Person 对象,它拥有一个属性值__proto__,而且__proto__是一个对象,包含两个属性值 constructor 和__proto__spa
console.log(p.__proto__.constructor); //function Person(){} console.log(p.__proto__.__proto__); //对象{},拥有不少属性值
p.__proto__.constructor 返回的结果为构造函数自己,p.__proto__.__proto__有不少参数 prototype
console.log(p.__proto__.__proto__)
咱们调用 constructor 属性,code
p.__proto__.__proto __.constructor 获得拥有多个参数的Object()函数,orm
Person.prototype 的隐式原型的 constructor 指向Object(),即 Person.prototype.__proto__.constructor == Object()对象
从 p.__proto__.constructor 返回的结果为构造函数自己获得 Person.prototype.constructor == Person()blog
因此 p.__proto__.__proto__== Object.prototype继承
即 p.b 打印结果为b,p没有b属性,会一直经过__proto__向上查找,最后当查找到 Object.prototype 时找到,最后打印出b,
向上查找过程当中,获得的是 Object.prototype,而不是 Function.prototype,找不到a属性,
因此结果为 undefined,这就是原型链,经过__proto__向上进行查找,最终到null结束
console.log(p.__proto__.__proto__.__proto__); //null console.log(Object.prototype.__proto__); //null
同理,得出如下结果
//Function function Function(){} console.log(Function); //Function() console.log(Function.prototype.constructor); //Function() console.log(Function.prototype.__proto__); //Object.prototype console.log(Function.prototype.__proto__.__proto__); //NULL console.log(Function.prototype.__proto__.constructor); //Object() console.log(Function.prototype.__proto__ === Object.prototype); //true