【问题标题】:Javascript Assign and delete propertiesJavascript 分配和删除属性
【发布时间】:2019-01-30 12:45:00
【问题描述】:

谁能解释一下这里到底发生了什么?

var myObject = {
  price: 20.99,
  get_price: function() {
    return this.price;
  }
};

var customObject = Object.create(myObject);
customObject.price = 19.99;
delete customObject.price;
console.log(customObject.get_price()); //returns 20.99

【问题讨论】:

    标签: javascript object properties assign


    【解决方案1】:

    这是由于prototype-chain 的后果而发生的。声明

    var customObject = Object.create(myObject);
    

    创建一个对象,其原型设置为myObject。现在您正在分配和删除属性price。但它不会改变其原型中已有的内容。

    您可以通过在删除属性price 之前将customObject 打印到控制台来尝试。您将看到该对象包含一个属性price,其值设置为19.99,但其__proto__ 属性的price 仍然是20.99。运行以下 sn-p,并在浏览器的控制台中观察输出。

    var myObject = {
      price: 20.99,
      get_price: function() {
        return this.price;
      }
    };
    
    var customObject = Object.create(myObject);
    customObject.price = 19.99;
    console.log(customObject);

    函数get_price返回this.price,它在当前对象中搜索属性price,如果没有找到,则递归遍历该属性的原型链。由于该属性存在于对象的直接原型中,因此返回值 20.99。

    【讨论】:

      【解决方案2】:

      Javascript 中的所有对象都有一个__proto__ 属性,称为它的原型。 (它与某些函数上的prototype 属性不同,原因我不会讨论。)

      原型链是在请求时查找某个名称的顺序。例如dog.bark 将在dog 中搜索'bark',但如果dog 没有'bark' 属性,它将在dog.__proto__ 中搜索'bark',依此类推,直到到达原型链

      使用方括号语法 ({}) 声明的新对象将 Object 作为其原型。

      函数Object.create(some) 返回一个以some 为原型的新对象。 (some 可以是null 来创建没有原型的对象)。

      var myObject = {
        price: 20.99,
        get_price: function() {
          return this.price;
        }
      };
      var customObject = Object.create(myObject);
      customObject.price = 19.99; // *
      delete customObject.price; // **
      console.log(customObject.get_price());
      

      * 中,对象 customObject 如下所示:

      customObject = {
        price: 19.99,
        __proto__: {
          price: 29.99,
          get_price: function() { return this.price; }
        }
      };
      

      ** 中,对象 customObject 如下所示:

      customObject = {
        __proto__: {
          price: 29.99,
          get_price: function() { return this.price; }
        }
      };
      

      delete operator只删除自己的属性,这意味着那些属性直接属于对象(而不是其原型)。

      因此,我们删除了price: 19.99,现在我们在尝试获取customObject.price 时得到price: 29.99(这是get_price 所做的)。

      如果我们调用myObject.get_price(),我们得到myObject.price,而在customObject.get_price(),我们得到customObject.price。虽然get_price函数实际上在customObject.__proto__内部,但函数调用中的特殊变量this指的是调用函数的对象,而不是函数所属的对象。

      如果您认为同一个函数可以属于不同的对象,这是有道理的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-11
        • 2012-10-24
        • 2020-07-29
        • 2014-01-21
        • 2021-11-23
        • 2016-01-05
        • 2020-07-08
        • 2010-09-17
        相关资源
        最近更新 更多