考虑以下示例:
var Container = function(param) {
this.member = param;
var privateVar = param;
if (!Container.prototype.stamp) { // <-- executed on the first call only
Container.prototype.stamp = function(string) {
return privateVar + this.member + string;
}
}
}
var cnt = new Container();
有什么方法可以确定对象
cnt
是否具有名为stamp
的方法,而又不知道它是从Container
实例化的吗? 最佳答案
您可以使用以下命令测试是否存在stamp
:
if (cnt.stamp) ...
或者您可以检查它是否具有
if (typeof cnt.stamp === 'function') ...