Function.prototype.a = 1;
Object.prototype.b = 2;
function A() {}
var a = new A();
console.log(a.a, a.b); // undefined, 2
console.log(A.a, A.b); // 1, 2
https://www.cnblogs.com/everlose/p/12930468.html
对于 new 出来的对象 a 的属性,原型链查找的顺序应该是
a 自身
a.proto 相当于 A.prototype
A.prototype.proto 相当于 Object.prototype
Object.prototype.proto 这个为 null,原型链查找到头。
对于 function 定义的函数 A 的属性,原型链查找顺序应该是
A 自身
A.proto 相当于 Function.prototype
Function.prototype.proto 等于 Object.prototype
Object.prototype.proto 这个为 null,原型链查找到头。
构造函数原型链
function G() {
}
function F() {
return new G()
}
a = new F();
console.log(a);
console.log(a instanceof F);//false
console.log(a instanceof G);//true关于构造函数:
一般构造函数不显式返回值,用户可以选择主动返回对象来覆盖正常的对象创建步骤
如果构造函数没有返回值:默认情况下 return this; 即返回创建的实例
如果返回简单数据类型:返回该实例
如果返回对象类型:返回这个对象类型,而不是实例
构造函数返回值有关
function A() {
this.a = 1
return {
a: 2
}
}
A.prototype.a = 3
const a = new A()
console.log(a.a)//a等于 A函数返回的对象{a:2}
console.log(a.constructor)//Object
console.log(a.__proto__)//Object.prototypefunction Parent() {
this.a = 'Parent'
}
function Child() {
this.a = 'Child'
}
Function.prototype.print = function() {
console.log(this.a)
}
Parent.print()//undefined
//Parent本身没有print这个方***随着原型链寻找,
//在Function的原型上找到了print方法,并执行
//实际上,执行print方法的是Function 不是Parent
//所以this.a指的是全局上的a 为undefined
//下面同理
Child.print()//undefined
var p = new Parent()
//找不到print 因为p的原型链上只有Object.prototype
p.print()//报错
京公网安备 11010502036488号