javascript中的instanseOf isPrototype setPrototypeOf create之间的关系

create

a = function () {
this.e = 1;
};
a.prototype.b = 3;
a.c = 2;
b = Object.create(a.prototype, {
d: {
value: 4,
configurable: true,
enumerable: false,
writable: true,
}
});
// b.__ptoto__ = a.prototype;
console.log(b.b) // 3
console.log(b.c) // undefined
console.log(b.c) // undefined 可以看出Object.create没有执行constructor
console.log(b.d) // 4

// =======================

b = new a();
new的对象直接是constructor而不是prototype
结果都是b.__proto__ = a.prototype
而new还会执行constructor

instanceOf
b instanceOf a
以前经常说b是不是a的实例,通过理解object instanceof constructor
instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。
a = function(){};b = function(){} b.prototype = new a(); c = new b();
c.__proto__ = b.prototype b.prototype.__proto__ = a.prototype
c instanceOf a

isPrototypeOf
prototypeObj.isPrototypeOf(object)
检测prototypeObj对象是否存在于object原型链上
a.prototype.isPrototypeOf(c);

setPrototypeOf
sub = function(){}; sup = function(){}; sup.prototype.a = 1;a = new sub();
Object.setPrototypeOf(sub.prototype, sup.prototype);
a.a // 1
a.__proto__ === sub.prototype sub.prototype.__proto__ = sup.prototype;
sup.prototype.isPrototypeOf(a)
另外一种通过create形式实现

sub = function(){}; sup = function(){}; sup.prototype.a = 1;
sub.prototype = Object.create(sup.prototype, {constructor: {
value: sub,
enumerable: false,
writable: true,
configurable: true
}});
a = new sub();

发表评论

电子邮件地址不会被公开。 必填项已用*标注