Google Chrome Object.defineProperty中的错误行为? [英] Wrong behaviour in Google Chrome Object.defineProperty?

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

问题描述



  var Player = function(高度){
var _height = height;

Object.defineProperty(this,'height',{
enumerable:false
,可配置:true
,可写:false
,get:function (){return _height;}
,set:function(val){_ height = val;}
});

var myPlayer = new Player(10);

即使defineProperty选项的可写属性设置为false,我也会得到以下错误:

无效的属性。一个属性不能同时拥有访问器,并且可写或具有值,#< Object>



当然,$ c> writable 设置为true,但是如果我删除可写行,错误消失。



我做错了什么,或者这是一个错误?这发生在谷歌浏览器版本30.0.1599.66上。

解决方案 Mozilla MDN for Object.defineProperty 澄清这:


对象中的属性描述符有两种主要特征:数据描述符和访问符描述符。数据描述符是一个具有值的属性,该值可能是可写的,也可能不是可写的。访问器描述符是由getter-setter函数对描述的属性。描述符必须是这两种口味之一;它不能同时存在。


这意味着您可以使用以下任何一种:




  • 可写和

  • get set



但是你不能使用它们的任何组合。在你的例子中,你指定了可写属性,这意味着它是一个数据描述符,它不允许 get set 属性。


I am trying to create an object with setters and getters, and this is my code:

var Player = function(height){
    var _height = height;

    Object.defineProperty(this, 'height', {
      enumerable: false
    , configurable: true
    , writable: false
    , get: function(){return _height;}
    , set: function(val){_height = val;}
    });
}

var myPlayer = new Player(10);

Even though the writable property of the defineProperty options is set to false, I get the following error:

Invalid property. A property cannot both have accessors and be writable or have a value, #<Object>

The same is happening when the writable is set to true of course, but the error disappears if I remove the writable line.

Am I doing something wrong, or is this a bug? This is happening on Google Chrome, Version 30.0.1599.66

解决方案

The Mozilla MDN for Object.defineProperty clarifies this:

Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.

This means, that you can use either one of those:

  • writable and value
  • get and set

But you cannot use any combination of them. In your example, you specify the writable attribute, which means that it is a data descriptor, which disallows get and set attributes.

这篇关于Google Chrome Object.defineProperty中的错误行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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