1 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超6個贊
您使用的控制臺只記錄對象自己的屬性值,而不是來自原型的屬性值。不一定適用于所有控制臺:
class People {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
Object.defineProperty(People.prototype, 'salary', {
value: 3000,
enumerable: true,
writable: true
});
var p = new People('Jack', 46);
//compare with the browser console
console.log(p);
至于為什么屬性“不可枚舉”——那是因?yàn)镺bject#propertyIsEnumerable沒有遍歷原型鏈:
var a = { foo: 1 };
var b = Object.create(a);
b.bar = 2;
console.log(`a:
a.foo: ${a.foo}
a.hasOwnProperty("foo"): ${a.hasOwnProperty("foo")}
a.propertyIsEnumerable("foo"): ${a.propertyIsEnumerable("foo")}`);
console.log(`b:
b.foo: ${b.foo}
b.hasOwnProperty("foo"): ${b.hasOwnProperty("foo")}
b.propertyIsEnumerable("foo"): ${b.propertyIsEnumerable("foo")}
b.bar: ${b.bar}
b.hasOwnProperty("bar"): ${b.hasOwnProperty("bar")}
b.propertyIsEnumerable("bar"): ${b.propertyIsEnumerable("bar")}`);
至于為什么當(dāng)你改變它時(shí)它“變得可枚舉”——事實(shí)是它不會——當(dāng)你向?qū)ο筇砑右粋€新屬性時(shí),你現(xiàn)在得到的是那個,而不是原型中的那個。原型屬性沒有改變:
var a = { foo: 1 };
var b = Object.create(a);
console.log(`b before adding a property:
b.foo: ${b.foo}
b.hasOwnProperty("foo"): ${b.hasOwnProperty("foo")}
b.propertyIsEnumerable("foo"): ${b.propertyIsEnumerable("foo")}`);
b.foo = 2;
console.log(`b after adding a property:
b.foo: ${b.foo}
b.hasOwnProperty("foo"): ${b.hasOwnProperty("foo")}
b.propertyIsEnumerable("foo"): ${b.propertyIsEnumerable("foo")}`);
console.log(`a after adding a property to b:
b.foo: ${a.foo}`);
添加回答
舉報(bào)