2009-05-19 41 views
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生产出预期的效果?

回答

4

我想你可能想要查看道格拉斯Crockford的关于在JavaScript中继承写作。他有一些在他的书中JavaScript: The Good Parts,以及一些在他YUI剧院讲座< http://developer.yahoo.com/yui/theater/>。从那些从衍生它们的对象的区分对象的属性,参见hasOwnProperty() method。克罗克福德似乎认为在JavaScript中使用经典的继承是可能的,而不是去开发语言能力的最佳途径。也许这会给你如何去解决你想要完成的想法。无论祝你好运!

克罗克福德上继承:

+0

谢谢。 :) hasOwnProperty()就像一个魅力。 – Stefan 2009-05-19 18:58:03