如何在函数中查找属性



我想知道函数是否有特定的属性。"in"运算符应该完成以下工作:MSD报价:

如果指定的属性在指定的对象或其原型链中,in运算符将返回true。

所以-你能解释一下这个代码的结果吗?

function Shape() {
aaa = 10
}
Shape.prototype.bbb = 20
function Square() {}
Square.prototype = Object.create(Shape.prototype)
Square.prototype.constructor = Square;
console.log('aaa' in Shape) // false???
console.log('bbb' in Shape) // false???
console.log('aaa' in Square) // false???
console.log('bbb' in Square) // false???```

in不检查class本身的属性。它检查类实例中的属性。

function Shape() {
aaa = 10
}
Shape.prototype.bbb = 20
function Square() {}
Square.prototype = Object.create(Shape.prototype)
Square.prototype.constructor = Square;
const instance = new Square();
console.log('aaa' in instance) // false
console.log('bbb' in instance) // true

在这里,当您将属性分配给某个function的原型时,并不意味着该函数将具有这些属性。原型上的这些属性将添加到对象创建的实例中。

是的,如果您将属性分配给函数本身,则它将使用in显示

function test(){
}
test.prototype.x = 3;
test.something = 5
console.log(Object.keys(test)) //["something"]
console.log("something" in test) //true

最新更新