seahorsepip
seahorsepip

Reputation: 4809

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?

Upvotes: 0

Views: 500

Answers (3)

trincot
trincot

Reputation: 350137

This code reveals this:

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

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

var example = new test();

for (prop of ['a', 'b', 'c']) {
    if (example.hasOwnProperty(prop)) console.log(prop + ' is owned by the object');
    if (test.prototype.hasOwnProperty(prop)) console.log(prop + ' is owned by the object prototype');
}

Upvotes: 1

jfriend00
jfriend00

Reputation: 707218

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")

Upvotes: 1

10100111001
10100111001

Reputation: 1832

You can check the properties within the object and its prototype by using the Object.keys method.

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

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

var example = new test();

console.log(Object.keys(example));
console.log(Object.keys(example.__proto__));

Upvotes: 1

Related Questions