function Name(first, last) {
  this.first = first;
  this.last = last;
  this.fullName = first + " " + last
}

Name.prototype = {
  get fullName() {
    return this.first + " " + this.last;
  },

  set fullName(name) {
    var names = name.split(" ");
    this.first = names[0];
    this.last = names[1];
  }
};

var person = new Name("Foo", "Bar");
// person.fullName = "Foo Bar"
person.hasOwnProperty("fullName") // false

有没有办法返回属性?

最佳答案

正如InvernoMuto指出的那样,Object.hasOwnProperty("fullName")返回false,因为它不是person的自身属性;它是通过原型(prototype)链继承的。在构造函数中使用this.fullName = "...";时,您是在调用继承的setter,而不是添加新属性。

如果要查找此类属性,可以:

  • 使用for..in循环:

  • for (var prop in person) {
        // this will iterate over EVERY property in person's prototype chain
    }
    
  • 将属性附加到构造函数中:



  • function Name(first, last) {
      this.first = first;
      this.last = last;
    
      Object.defineProperty(this, "fullName", {
        get: function() {
          return this.first + " " + this.last;
        },
        set: function(name) {
          var names = name.split(" ");
          this.first = names[0];
          this.last = names[1];
        }
      });
    }
    
    var person = new Name("Ronald", "McDonald");
    console.log(person.hasOwnProperty("fullName")); // true


  • 使用那里的get / set语法在构造函数中创建一个全新的对象。在这种情况下,我们将不使用new关键字,而只是调用以下函数:


  • function Name(first, last) {
        return {
            first: first,
            last: last,
    
            get fullName() { return this.first + " " + this.last; },
            set fullName(name) {
                var names = name.split(" ");
                this.first = names[0];
                this.last = names[1];
            }
        };
    };
    
    var person = Name("Ronald", "McDonald");
    console.log(person.hasOwnProperty("fullName")); // true

    07-25 21:52
    查看更多