javascript中的Object.create方法 [英] Object.create method in javascript

查看:155
本文介绍了javascript中的Object.create方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为javascript的初学者,我试图从这里理解Object.create()方法

Being a beginner in javascript, i tried to understand Object.create() method from here

https://developer-new.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object / create

在示例代码中,第18行。创建一个accessable属性,其writeable设置为true。我还读到只有数据描述符可写。

In the example code, line 18. A accessor property is created with writable set to true. I also read that writable is only for data descriptors.

尝试运行,

var o = Object.create(Object.prototype, {
  // foo is a regular "value property"
  foo: { 
    writable:true, configurable:true, value: "hello" 
  },
  // bar is a getter-and-setter (accessor) property
  bar: {
    writable: true,
    configurable: false,
    get: function() { return 10 },
    set: function(value) { console.log("Setting `o.bar` to", value) }
  }
  });
console.log(o); 

我收到无效的属性错误

推荐答案

问题是可写设置 / get 是互斥的。该代码会在Chrome中生成此有用的错误:

The issue is that writable and set/get are mutually exclusive. The code generates this helpful error in Chrome:

Invalid property. A property cannot both have accessors and be writable...

这有一定的逻辑意义:如果你有设置 / 获取属性的访问者,该属性永远不会被写入和/或读取,因为任何读取/写入的尝试都将被访问者函数拦截。如果您将属性定义为可写 并且为其提供访问者功能,则您同时说:

This makes some logical sense: if you have set/get accessors on a property, that property is never going to be written to and/or read from, because any attempts to read/write it will be intercepted by the accessor functions. If you define a property as writable and give it accessor functions, you are simultaneously saying:


  1. 此属性的值可以直接更改,和

  2. 阻止所有读取和/或写入此属性的尝试;相反,使用这些函数。

错误只是阻止你指定矛盾。我假设你写了一个getter和setter,你真的不希望该属性是 writable 。只需删除该行,您的代码就可以完美运行。

The error is simply stopping you from specifying a contradiction. I assume from the fact that you wrote a getter and setter, you don't really want the property to be writable. Just remove that line, and your code runs perfectly.

这篇关于javascript中的Object.create方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆