Consider the following sample:
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();
Is there any way to determine whether the object cnt
has a method named stamp
without knowing that it is instantiated from Container
?
You can test for the existence of stamp
with:
if (cnt.stamp) ...
or you can check whether it is a function with
if (typeof cnt.stamp === 'function') ...
You can use hasOwnProperty
o = new Object();
o.prop = 'exists';
o.hasOwnProperty('prop'); // returns true
o.hasOwnProperty('toString'); // returns false
o.hasOwnProperty('hasOwnProperty'); // returns false
精彩评论