seahorsepip seahorsepip - 3 months ago 7
Javascript Question

How to check if a value in this is a prototype value in javascript?

I've got the following code:

function test() {
this.a = 5;
this.b = 6;
}

test.prototype.b = 10;
test.prototype.c = 12;

var example = new test();





How do I find out if
example.something
:

A. has only a value in the function object?

B. has only a value in the prototype?

C. has a value in both the function object and prototype?

Answer

You can test the prototype to see if the value is specified in the prototype with this:

example.constructor.prototype.b

or

Object.getPrototypeOf(example).b 

You can test if the property is directly on the object itself (e.g. not inherited or on the direct prototype) with:

example.hasOwnProperty("b")