How do I find the values ​​of "prototype" in javascript?

I am using the following function to determine the values ​​that belong to the constructor of an object instead of the object itself.

function isAPrototypeValue(object, key ) {
  return !(object.constructor && object.constructor.prototype[key]);
}

      

it will work like this:

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 using 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 in itself is not a big problem, but ...

if i expanded the result like this:

result.custom_value = 'custom'
result.another_value = 'another'

      

I would expect to be able to distinguish between values ​​related 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 output the expected results?

0


a source to share


1 answer


I think you might want to consider Douglas Crockford, who wrote about inheritance in JavaScript. He has some of his JavaScript books : the good parts , and some in his lectures on YUI theater < http://developer.yahoo.com/yui/theater/ >. To distinguish the properties of objects from the objects of the objects from which they are derived, see Method hasOwnProperty()

. Crockford seems to argue that using classical inheritance in JavaScript is possible, but not the best way to leverage the power of languages. Perhaps this will give you an idea of ​​how to decide what you are trying to accomplish. Best of all luck!

Crockford by inheritance:



+4


a source







All Articles