使用setter方法的JavaScript属性不是真正的属性吗?

iks*_*ose 8 javascript inheritance

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
Run Code Online (Sandbox Code Playgroud)

有办法归还物业吗?

ale*_*dro 6

hasOwnProperty不会检查对象的原型链,在您的案例中get,set并通过原型链继承

hasOwnProperty

来自Object的每个对象都继承hasOwnProperty方法.此方法可用于确定对象是否具有指定的属性作为该对象的直接属性; 与in运算符不同,此方法不会检查对象的原型链.

function Name(first, last) {
    this.first = first;
    this.last = last;
    this.fullName = first + " " + last;
}
var person = new Name("Foo", "Bar");
console.log(person.fullName);
console.log(person.hasOwnProperty("fullName")); // true
console.log(Name.prototype.hasOwnProperty("fullName")); // false

for (var prop in person) {
    console.log(prop);
}

console.log('');

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 person2 = new Name("Foo", "Bar");
console.log(person2.fullName);
console.log(person2.hasOwnProperty("fullName")); // false
console.log(Name.prototype.hasOwnProperty("fullName")); // true
Run Code Online (Sandbox Code Playgroud)

引用@JLRishe

当你使用this.fullName ="..."; 在构造函数中,您正在调用继承的setter,而不是添加新属性.

如果要查找此类属性,可以使用for ... in语句:

for (var prop in person) {
    console.log(prop);
}
Run Code Online (Sandbox Code Playgroud)


JLR*_*she 3

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

如果您想找到此类属性,您可以:

  1. 使用for..in循环:
for (var prop in person) {
    // this will iterate over EVERY property in person's prototype chain
}
Run Code Online (Sandbox Code Playgroud)
  1. 在构造函数中附加属性:

for (var prop in person) {
    // this will iterate over EVERY property in person's prototype chain
}
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)