如何在javascript中检查一个值是否为原型值

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

本文关键字:一个 是否 原型 javascript 检查      更新时间:2023-09-26

我有以下代码:

function test() {
    this.a = 5;
    this.b = 6;
}
test.prototype.b = 10;
test.prototype.c = 12;
var example = new test();


我怎么知道example.something:

在函数对象中只有一个值?

B。在原型中只有一个值?

C。在函数对象和原型中都有一个值?

你可以测试这个原型,看看这个值是否在原型中指定了:

example.constructor.prototype.b

Object.getPrototypeOf(example).b 

你可以测试属性是否直接在对象本身上(例如,不是继承的或在直接原型上):

example.hasOwnProperty("b")

您可以使用Object.keys方法检查对象及其原型中的属性。

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__));

下面的代码显示:

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');
}

相关文章: