0
我用下面的函数来检测属于一个对象的构造而不是对象本身的值。如何找到在javascript“原型”值?
function isAPrototypeValue(object, key) {
return !(object.constructor && object.constructor.prototype[key]);
}
这会工作如下:
Array.prototype.base_value = 'base'
var array = new Array;
array.custom_value = 'custom'
alert(isAPrototypeValue(array, 'base_value')) // true
alert(isAPrototypeValue(array, 'custom_value')) // false
但,当我开始使用继承:
function Base() {
return this
};
Base.prototype.base_value = 'base';
function FirstSub() {
return this
};
FirstSub.prototype = new Base();
FirstSub.prototype.first_value = 'first';
function SubB() {
return this
};
SecondSub.prototype = new FirstSub();
SecondSub.prototype.second_value = 'second';
result = new SecondSub();
,我叫
alert(result.constructor)
我会得到基地而不是预期的SecondSub,这本身不是什么大问题,但是......
如果我延长结果这样的:
result.custom_value = 'custom'
result.another_value = 'another'
我本来预期能够属于结果属于SecondSub,FirstSub和基地或值的值之间进行区分;
例如。
alert(isAPrototypeValue(result, 'custom_value')) // false (as expected)
alert(isAPrototypeValue(result, 'base_value')) // true (as expected)
alert(isAPrototypeValue(result, 'first_value')) // true extend, but it is false
alert(isAPrototypeValue(result, 'second_value')) // true extend, but it is false
如何更改isAPrototypeValue生产出预期的效果?
谢谢。 :) hasOwnProperty()就像一个魅力。 – Stefan 2009-05-19 18:58:03