Reputation: 9599
I use the following function to detect values that belonged to an object's constructor instead of the object itself.
function isAPrototypeValue(object, key ) {
return !(object.constructor && object.constructor.prototype[key]);
}
this would work as follows:
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
But when I started to use inheritance:
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();
and I called
alert( result.constructor )
I would get Base instead of the expected SecondSub, which itself is not a big problem, But...
if I extended result like this:
result.custom_value = 'custom'
result.another_value = 'another'
I would have expected to be able to distinguish between values that belong to result or values that belong to SecondSub, FirstSub and Base;
eg.
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
How can I change isAPrototypeValue to churn out the expected results?
Upvotes: 0
Views: 172
Reputation: 34013
I think you might want to review Douglas Crockford's writing on inheritance in JavaScript. He has some in his book JavaScript: The Good Parts, and some in his lectures on YUI Theater <http://developer.yahoo.com/yui/theater/>. For distinguishing objects properties from those of the objects from which they are derived, see the hasOwnProperty()
method. Crockford seems to argue that using classical inheritance in JavaScript is possible, but not the best way to go about exploiting the languages capabilities. Perhaps this will give you ideas on how to go about addressing what you're trying to accomplish. Best of luck regardless!
Crockford on Inheritance:
Upvotes: 4