【发布时间】:2019-03-09 00:30:55
【问题描述】:
在这里找到答案:Javascript what is property in hasOwnProperty?
在这篇帖子How to display all methods of an object? 中,它说“您可以使用 Object.getOwnPropertyNames() 来获取属于对象的所有属性,无论是否可枚举”。通过示例,我们可以看到所有属性都包括列出的Math 对象的方法。我试过了,结果一样。
然后我尝试定义自己的对象并以相同的方式列出它的属性,但是为什么没有列出方法?例如对于console.log(Object.getOwnPropertyNames(animal)),为什么它只返回["name", "weight"],而不包括"eat", "sleep" and wakeUp?
function Animal(name, weight) {
this.name = name;
this.weight = weight;
}
Animal.prototype.eat = function() {
return `${this.name} is eating!`;
}
Animal.prototype.sleep = function() {
return `${this.name} is going to sleep!`;
}
Animal.prototype.wakeUp = function() {
return `${this.name} is waking up!`;
}
var animal = new Animal('Kitten', '5Kg');
console.log(Object.getOwnPropertyNames(animal)); // ["name", "weight"]
另一个例子是,为什么下面的返回属于超类的属性,因为它是从Shape继承的Triangle。对于console.log(Object.getOwnPropertyNames(triangle));,我们是否假设只得到["a", "b", "c"] 而没有"type"?
class Shape {
constructor(type) {
this.type = type;
}
getType() {
return this.type;
}
}
class Triangle extends Shape {
constructor(a, b, c) {
super("triangle");
this.a = a;
this.b = b;
this.c = c;
}
getParamiter() {
return this.a + this.b + this.c;
}
}
const triangle = new Triangle(1,2,3);
console.log(Object.getOwnPropertyNames(triangle)); //["type", "a", "b", "c"]
【问题讨论】:
-
getOwnPropertyNames()不会返回从原型继承的属性。这就是“拥有”的意思——它只返回对象本身的属性。 -
查看developer.mozilla.org/en-US/docs/Web/JavaScript/… 获取更多属性/方法的选项
-
这部分You don't Know JS 书解释了发生了什么以及原型方法(它们只是另一个对象)如何链接到您使用
new创建的对象.它解释了原型继承的基本原理。
标签: javascript