为什么Object.getOwnPropertyNames()不起作用

时间:2019-03-09 00:30:56

标签: javascript

在这里找到答案: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"]

另一个例子是,为什么下一个返回属于超类的属性,因为它是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"]

1 个答案:

答案 0 :(得分:3)

名称中带有“ 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)));