javascript - 使用instanceof测试对象

标签 javascript

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 对象在这里。

最佳答案

来自MDN entry on instanceof :

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/

相关文章:

javascript - 单击按钮时 Jquery/Animation 重新加载问题

javascript - 将 JQuery 模态对话框动态调整为 IFrame 内容

javascript - 为什么输入文本字段不出现

javascript - 数据表预提交 2 个字段

javascript 变量使用帮助

javascript - 使用 jquery 在 nvd3 中触发图例单击事件?

javascript - 需要按多选值数组进行分组

循环内的 JavaScript 闭包 – 简单的实际示例

javascript - 在插件函数中调用 html 数据集

javascript - JSF丰富:scrollableDataTable rowcount on javascript popop