var google = {
makeBeer : function(arg1,arg2){
alert([this instanceof google, arg1, arg2]);
}
}
google.makeBeer('water','soda');
当我检查this instanceof google
时,上面的内容不会发出警报,但当我这样做时,相同的代码会起作用。
var google = {
makeBeer : function(arg1,arg2){
alert([this instanceof Object, arg1, arg2]);
}
}
google.makeBeer('water','soda');
引用“this”是对象的实例,为什么不是 Google 对象
。在我的例子中,我如何确保该实例属于该特定对象。
更新同一问题:
var newWay = {}
google.makeBeer.call(newWay, 'pepsi', 'coke');
在上面的例子中,我将 newWay 对象传递给我的函数 makeBeer,我怎么知道它的 newWay 对象在这里。
最佳答案
The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.
因此,除非您使用唯一的构造函数创建对象,例如:
var newWay = new Way(); // assuming you have defined an object Way
其中newWay instanceof Way === true
,除了它是一个对象之外,您不能使用instanceof 来告诉您任何其他信息。
关于javascript - 使用instanceof测试对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15389345/