Javascript instanceof与共享原型
以下代码记录“true”4次:Javascript instanceof与共享原型,javascript,prototype,instanceof,Javascript,Prototype,Instanceof,以下代码记录“true”4次: var menuItem = { name: "New menuItem", }; function food(name) { if(name) this.name = name; //this.resourceType = "food"; } food.prototype = menuItem; function drink(name) { if(name) this.name = name; //this.resou
var menuItem = {
name: "New menuItem",
};
function food(name) {
if(name) this.name = name;
//this.resourceType = "food";
}
food.prototype = menuItem;
function drink(name) {
if(name) this.name = name;
//this.resourceType = "drink";
}
drink.prototype = menuItem;
var burger = new food();
var coke = new drink();
console.log(buger instanceof food);
console.log(burger instanceof drink);
console.log(coke instanceof food);
console.log(coke instanceof drink);
但是,如果我注释掉以下两行:
//food.prototype = menuItem;
//drink.prototype = menuItem;
然后代码执行我想要的操作,并为“buger instanceof food”和“coke instanceof drink”记录true
当menuItem与食物或饮料共享同一原型(menuItem)时,是否有方法检查menuItem是否是正确的食物或饮料实例
我不希望这样存储类型:
this.resourceType = "food";
如果有更好的方法,请为每个构造函数创建一个新对象作为该构造函数的
原型,并让每个新原型对象使用菜单项作为其原型:
food.prototype = Object.create(menuItem);
因此,食品
实例和饮料
实例的原型链现在看起来像:
[food instance] > [food prototype] > [menuItem]
[drink instance] > [drink prototype] > [menuItem]
旧链条看起来像:
[food instance] > [menuItem]
[drink instance] > [menuItem]
正如您所看到的,在旧链中,food
实例和drink
实例实际上具有相同的原型父对象,因此food
构造的对象和drink
构造的对象具有相同的原型父对象。在新系统下,食物
和饮料
有各自的原型父母
MDN对
的实例有很好的描述:
instanceof
操作符测试对象的原型链中是否包含构造函数的prototype
属性
因此,当您测试饮料的汉堡实例时,您正在测试的是汉堡的原型链中的饮料.prototype
。以前,drink.prototype
等于menuItem
,所以您实际上是在测试burger
原型链中的“ismenuItem
”。现在,饮料。原型
是它自己独特的价值,与食品分开。原型
,所以结果是错误
你能给我看看旧的原型连锁店是什么样子吗?@Jimmay补充了更多的解释。你有一些关于汉堡/布格的拼写错误。