Reputation: 4809
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
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
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
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