在这篇文章中如何显示一个对象的所有方法?,它说“您可以使用 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"]Run Code Online (Sandbox Code Playgroud)
另一个例子是,为什么下面的一个返回属于超类的属性,因为它是Triangle从Shape. 因为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"]Run Code Online (Sandbox Code Playgroud)
所有名称中带有“own”的对象方法只查看对象中直接存在的属性,而不是从原型继承的属性。
您可以使用Object.getPrototypeOf()获取原型,然后调用Object.getOwnProperties()它。
那只会得到直接原型的方法。如果您想要整个链,则需要编写一个循环,该循环会一直调用getPrototypeOf()直到到达Object.
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!`;
}
function Gorilla(name, weight) {
Animal.call(this, name, weight);
}
Gorilla.prototype = Object.create(Animal.prototype);
Gorilla.prototype.constructor = Gorilla;
Gorilla.prototype.climbTrees = function () {
return `${this.name} is climbing trees!`;
}
Gorilla.prototype.poundChest = function() {
return `${this.name} is pounding its chest!`;
}
Gorilla.prototype.showVigour = function () {
return `${Animal.prototype.eat.call(this)} ${this.poundChest()}`;
}
Gorilla.prototype.dailyRoutine = function() {
return `${Animal.prototype.wakeUp.call(this)} ${this.poundChest()} ${Animal.prototype.eat.call(this)} ${Animal.prototype.sleep.call(this)}`;
}
var animal = new Animal('Kitten', '5Kg');
console.log(Object.getOwnPropertyNames(animal)); // ["name", "weight"]
console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(animal)));
var gorilla = new Gorilla('George', '160Kg');
console.log(Object.getOwnPropertyNames(gorilla)); console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(gorilla)));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1411 次 |
| 最近记录: |