JavaScript的Object.defineProperty详解

=与Object.defineProperty

为JavaScript对象新增或者修改属性,有两种不同方式:直接使用=赋值或者使用Object.defineProperty()定义。如下:

// 示例1
var obj = {};

// 直接使用=赋值
obj.a = 1;

// 使用Object.defineProperty定义
Object.defineProperty(obj, "b",
{
 value: 2
});

console.log(obj) // 打印"{a: 1, b: 2}"

这样看两者似乎没有区别,对吧?但是,如果使用Object.getOwnPropertyDescriptor()查看obj.a与obj.b的属性的描述描述符(property descriptor)时,会发现=与Object.defineProperty并不一样:

// 示例2
var obj = {};

obj.a = 1;

Object.defineProperty(obj, "b",
{
 value: 2
});

console.log(Object.getOwnPropertyDescriptor(obj, "a")); // 打印"{value: 1, writable: true, enumerable: true, configurable: true}"
console.log(Object.getOwnPropertyDescriptor(obj, "b")); // 打印"{value: 2, writable: false, enumerable: false, configurable: false}"

可知,使用=赋值时,属性的属性描述符value是可以修改的,而writable、enumerable和configurable都为true。

而使用Object.defineProperty()定义的属性的属性描述符writable、enumerable和configurable默认值为false,但是都可以修改。对于writable、enumerable和configurable的含义,从名字就不难猜中,后文也会详细介绍。

使用=赋值,等价于使用Object.defineProperty()定义时,同时将writable、enumerable和configurable设为true。代码示例3和4是等价的:

// 示例3
var obj = {};

obj.name = "Fundebug";
console.log(Object.getOwnPropertyDescriptor(obj, "name")); // 打印{value: "Fundebug", writable: true, enumerable: true, configurable: true}
// 示例4
var obj = {};

Object.defineProperty(obj, "name",
{
 value: "Fundebug",
 writable: true,
 enumerable: true,
 configurable: true
});
console.log(Object.getOwnPropertyDescriptor(obj, "name")); // 打印{value: "Fundebug", writable: true, enumerable: true, configurable: true}

Object.defineProperty()

使用Object.defineProperty()定义时若只定义value,则writable、enumerable和configurable默认值为false。代码示例5和6是等价的:

// 示例5
var obj = {};

Object.defineProperty(obj, "name",
{
 value: "Fundebug"
});
console.log(Object.getOwnPropertyDescriptor(obj, "name")); // 打印{value: "Fundebug", writable: false, enumerable: false, configurable: false}
// 示例6
var obj = {};

Object.defineProperty(obj, "name",
{
 value: "Fundebug",
 writable: false,
 enumerable: false,
 configurable: false
});
console.log(Object.getOwnPropertyDescriptor(obj, "name")); // 打印{value: "Fundebug", writable: false, enumerable: false, configurable: false}

由于writable、enumerable和configurable都是false,导致obj.name属性不能赋值、不能遍历而且不能删除:

// 示例7
var obj = {};

Object.defineProperty(obj, "name",
{
 value: "Fundebug"
});

// writable为false,无法赋值
obj.name = "云麒";
console.log(obj.name); // 打印"Fundebug"

// enumerable为false,无法遍历
console.log(Object.keys(obj)); // 打印"[]"

// configurable为false,无法删除
delete obj.name;
console.log(obj.name); // 打印"Fundebug"

若在严格模式(“use strict”)下,示例7中的代码会报错,下文可见。

writable

writable为false时,属性不能再次赋值,严格模式下会报错“Cannot assign to read only property”

// 示例8
"use strict"

var obj = {};

Object.defineProperty(obj, "name",
{
 value: "Fundebug",
 writable: false,
 enumerable: true,
 configurable: true
});

obj.name = "云麒"; // 报错“Uncaught TypeError: Cannot assign to read only property 'name' of object '#<Object>'”

writable为true时,属性可以赋值,这一点读者不妨自行测试。

enumerable

enumerable为false时,属性不能遍历:

// 示例9
"use strict"

var obj = {};

Object.defineProperty(obj, "name",
{
 value: "Fundebug",
 writable: true,
 enumerable: false,
 configurable: true
});

console.log(Object.keys(obj)) // 打印"[]"

enumerable为true时,属性可以遍历,这一点读者不妨自行测试。

configurable

enumerable为false时,属性不能删除,严格模式下会报错“Cannot delete property”:

// 示例10
"use strict"

var obj = {};

Object.defineProperty(obj, "name",
{
  value: "Fundebug",
  writable: true,
  enumerable: true,
  configurable: false
});

delete obj.name // 报错“Uncaught TypeError: Cannot delete property 'name' of #<Object>”

enumerable为true时,属性可以删除,这一点读者不妨自行测试。

writable与configurable

当writable与enumerable同时为false时,属性不能重新使用Object.defineProperty()定义,严格模式下会报错“Cannot redefine property”:

// 示例11
"use strict"

var obj = {};

Object.defineProperty(obj, "name",
{
  value: "Fundebug",
  writable: false,
  configurable: false
})

Object.defineProperty(obj, "name",
{
  value: "云麒"
}) // 报错“Uncaught TypeError: Cannot redefine property: name”

当writable或者enumerable为true时,属性可以重新使用Object.defineProperty()定义,这一点读者不妨自行测试。

本文所有代码示例都在Chrome 67上测试。

参考

Object.defineProperty()

Object.getOwnPropertyDescriptor()

StackOverflow: Why can't I redefine a property in a Javascript object?

(0)

相关推荐

  • 实时监控文本框输入字数的实例代码

    需求:实时监控文本输入框的字数,并加以限制 1.实时监控当前输入字数,直接使用onkeyup事件方法,给输入框加maxlength属性限制长度.如: <div> <textarea id="txt" maxlength="10"></textarea> <p><span id="txtNum">0</span>/10</p> </div> var tx

  • 使用javascript实现监控视频播放并打印日志

    最近在做一个项目,要求监控视频的播放事件并能够打印LOG日志,经过一番思索,使用javascript实现了此功能,代码如下: HTML: 复制代码 代码如下: <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>Multi Source</tit

  • 使用Object.defineProperty实现简单的js双向绑定

    缘起 前几天在看一些流行的迷你mvvm框架(比如avalon.js. vue.js 这种较轻的框架,而非Angularjs.Emberjs这种较重的框架)的实现.现代流行的mvvm框架一般都会将数据双向绑定(two-ways data binding)做掉,作为框架自身的一个卖点( Ember.js 貌似是不支持数据双向绑定的.),而且每种框架双向数据绑定的实现方式都不太一致,比如Anguarjs内部使用的是 脏检查 ,而avalon.js内部实现方式的本质是设置 属性访问器 . 这里不打算具体

  • JS实现监控微信小程序的原理

    原理 之前也做过浏览器web端的SDK数据埋点上报,其实原理大同小异:通过劫持原始方法,获取需要上报的数据,最后再执行原始方法,这样就能实现无痕埋点. 举个例子:我希望监控所有web页面的ajax请求,每次发送ajax,都需要在控制台打印出发送的url 平时我们开发,发送ajax一般用的都是封装好的库,例如jQuery,Axios等,然而这些库,底层仍然用的是浏览器原生的XMLHttpRequest对象,因此,我们只需要修改XMLHttpRequest对象即可 注意:由于JS的灵活性,修改原生方

  • js中Object.defineProperty()方法的不详解

    菜菜: "老大,那个, Object.defineProperty 是什么鬼?" 假设我们有个对象 user ; 我们要给它增加一个属性 name , 我们会这么做 var user = {}; user.name="狂奔的蜗牛"; console.log(user);//{name: "狂奔的蜗牛"} 如果想要增加一个sayHi方法叻? user.sayHi=function () { console.log("Hi !")

  • 使用Javascript监控前端相关数据的代码

    本篇文章介绍了Javascript监控前端相关数据,项目开发完成外发后,没有一个监控系统,我们很难了解到发布出去的代码在用户机器上执行是否正确,所以需要建立前端代码性能相关的监控系统. 所以我们需要做以下的一些模块: 一.收集脚本执行错误 function error(msg,url,line){ var REPORT_URL = "xxxx/cgi"; // 收集上报数据的信息 var m =[msg, url, line, navigator.userAgent, +new Dat

  • 关于angular js_$watch监控属性和对象详解

    $Watch:(监听一个model,当一个model每次改变时,都会触发第二个函数) $watch('watchFn',watchAction,deepWatch) watchFn:带有Angular 表达式或者函数的字符串,它会返回被监控的数据模型的当前值. watchAction: 一个函数function(newValue,oldValue){},当watchFn 发生变化时会被调用 deepWatch:默认为false,监听数组的某个元素或者对象的属性时设置为true; 监控一个属性:

  • 监控 url fragment变化的js代码

    当然,页面最好不要刷新,但是,拷贝一下浏览器的链接,又希望是下次能定位到你播发的那个视频.方法很简单,改变一下 url 的 fragment 就可以了. 监听fragment 的变化是这类编程的核心.在主流的浏览器(IE firefox)里面 都有一个 onhashchange 的事件监听 fragment 的变化. 但是,他们的行为有些差异.在IE8 以前的 IE版本里面,当 window.location 对象迅速变化的情况下,onhashchange 不会触发,非常奇怪的bug. 下面我写

  • JS使用对象的defineProperty进行变量监控操作示例

    本文实例讲述了JS使用对象的defineProperty进行变量监控操作.分享给大家供大家参考,具体如下: 以前觉得检测变量angular的$watch还挺好用的,但是一旦离开angular就无法下手了,今天看到一个方法,觉得挺好的,可能还 有别的办法,我会继续探索的 贴上代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <tit

  • JS监控关闭浏览器操作的实例详解

    JS监控关闭浏览器操作的实例详解 需求如下: 用户关闭浏览器通知后台. 方案如下: 1.采用js监控关闭浏览器操作. 2.用户关闭浏览器的时候发ajax请求到后台,执行相应的业务操作 代码如下: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> &l

随机推荐