Object.definedProperty

该方法允许精确添加或修改对象的属性。通过赋值操作添加的普通属性是可枚举的,能够在属性枚举期间呈现出来(for...in 或 Object.keys 方法), 这些属性的值可以被改变,也可以被删除。这个方法允许修改默认的额外选项(或配置)。默认情况下,使用 Object.defineProperty() 添加的属性值是不可修改的。

语法

Object.defineProperty(obj, prop, descriptor)

参数
obj
要在其上定义属性的对象。
prop
要定义或修改的属性的名称。
descriptor
将被定义或修改的属性描述符。 返回值
被传递给函数的对象。

属性描述符

对象里目前存在的属性描述符有两种主要形式:数据描述符和存取描述符。数据描述符是一个具有值的属性,该值可能是可写的,也可能不是可写的。存取描述符是由getter-setter函数对描述的属性。描述符必须是这两种形式之一;不能同时是两者。

数据描述符和存取描述符均具有以下可选键值:

configurable
当且仅当该属性的 configurable 为 true 时,该属性描述符才能够被改变,同时该属性也能从对应的对象上被删除。默认为 false。 enumerable
当且仅当该属性的enumerable为true时,该属性才能够出现在对象的枚举属性中。默认为 false。 数据描述符同时具有以下可选键值: value
该属性对应的值。可以是任何有效的 JavaScript 值(数值,对象,函数等)。默认为 undefined。
writable
当且仅当该属性的writable为true时,value才能被赋值运算符改变。默认为 false。 存取描述符同时具有以下可选键值: get
一个给属性提供 getter 的方法,如果没有 getter 则为 undefined。当访问该属性时,该方法会被执行,方法执行时没有参数传入,但是会传入this对象(由于继承关系,这里的this并不一定是定义该属性的对象)。
默认为 undefined。
set
一个给属性提供 setter 的方法,如果没有 setter 则为 undefined。当属性值修改时,触发执行该方法。该方法将接受唯一参数,即该属性新的参数值。
默认为 undefined。
如果一个描述符不具有value,writable,get 和 set 任意一个关键字,那么它将被认为是一个数据描述符。如果一个描述符同时有(value或writable)和(get或set)关键字,将会产生一个异常。

记住,这些选项不一定是自身属性,如果是继承来的也要考虑。为了确认保留这些默认值,你可能要在这之前冻结 Object.prototype,明确指定所有的选项,或者通过 Object.create(null)将__proto__属性指向null。

// 使用 __proto__
var obj = {};
var descriptor = Object.create(null); // 没有继承的属性
// 默认没有 enumerable,没有 configurable,没有 writable,隐式配置
descriptor.value = 'static';
Object.defineProperty(obj, 'key', descriptor); // 显式配置
Object.defineProperty(obj, "key", {
enumerable: false,
configurable: false,
writable: false,
value: "static"
});

描述符具有的键值

描述符 configurable enumerable value writable get set
数据描述符 Yes Yes Yes Yes No No
存取描述符 Yes Yes No No Yes Yes
var o = {}; // 创建一个新对象

// 在对象中添加一个属性与数据描述符的示例
Object.defineProperty(o, "a", {
value : 37,
writable : true,
enumerable : true,
configurable : true
});
// 对象o拥有了属性a,值为37 // 在对象中添加一个属性与存取描述符的示例
var bValue;
Object.defineProperty(o, "b", {
get : function(){
return bValue;
},
set : function(newValue){
bValue = newValue;
},
enumerable : true,
configurable : true
}); o.b = 38;
// 对象o拥有了属性b,值为38 // o.b的值现在总是与bValue相同,除非重新定义o.b // 数据描述符和存取描述符不能混合使用
Object.defineProperty(o, "conflict", {
value: 0x9f91102,
get: function() {
return 0xdeadbeef;
}
});
// throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors

修改属性

Writable 属性

当writable属性设置为false时,该属性被称为“不可写”。它不能被重新分配。


var o = {}; // Creates a new object Object.defineProperty(o, 'a', {
value: 37,
writable: false
}); console.log(o.a); // logs 37
o.a = 25; // No error thrown

Enumerable属性

var o = {};
Object.defineProperty(o, "a", { value : 1, enumerable:true });
Object.defineProperty(o, "b", { value : 2, enumerable:false });
Object.defineProperty(o, "c", { value : 3 }); // enumerable defaults to false
o.d = 4; // 如果使用直接赋值的方式创建对象的属性,则这个属性的enumerable为true Object.keys(o); // ["a", "d"] o.propertyIsEnumerable('a'); // true
o.propertyIsEnumerable('b'); // false
o.propertyIsEnumerable('c'); // false

configurable属性

configurable特性表示对象的属性是否可以被删除,以及除writable特性外的其他特性是否可以被修改。


var o = {};
Object.defineProperty(o, "a", { get : function(){return 1;},
configurable : false } ); // throws a TypeError
Object.defineProperty(o, "a", {configurable : true});
// throws a TypeError
Object.defineProperty(o, "a", {enumerable : true});
// throws a TypeError (set was undefined previously)
Object.defineProperty(o, "a", {set : function(){}});
// throws a TypeError (even though the new get does exactly the same thing)
Object.defineProperty(o, "a", {get : function(){return 1;}});
// throws a TypeError
Object.defineProperty(o, "a", {value : 12}); console.log(o.a); // logs 1
delete o.a; // Nothing happens
console.log(o.a); // logs 1 //如果o.a的configurable属性为true,则不会抛出任何错误,并且该属性将在最后被删除。

添加多个属性值和默认值

var o = {};

o.a = 1;
// 等同于 :
Object.defineProperty(o, "a", {
value : 1,
writable : true,
configurable : true,
enumerable : true
}); // 另一方面,
Object.defineProperty(o, "a", { value : 1 });
// 等同于 :
Object.defineProperty(o, "a", {
value : 1,
writable : false,
configurable : false,
enumerable : false
});

setter和getter


function Archiver() {
var temperature = null;
var archive = []; Object.defineProperty(this, 'temperature', {
get: function() {
console.log('get!');
return temperature;
},
set: function(value) {
temperature = value;
archive.push({ val: temperature });
}
}); this.getArchive = function() { return archive; };
} var arc = new Archiver();
arc.temperature; // 'get!'
arc.temperature = 11;
arc.temperature = 13;
arc.getArchive(); // [{ val: 11 }, { val: 13 }] //or
var pattern = {
get: function () {
return 'I alway return this string,whatever you have assigned';
},
set: function () {
this.myname = 'this is my name string';
}
}; function TestDefineSetAndGet() {
Object.defineProperty(this, 'myproperty', pattern);
} var instance = new TestDefineSetAndGet();
instance.myproperty = 'test'; // 'I alway return this string,whatever you have assigned'
console.log(instance.myproperty);
// 'this is my name string'
console.log(instance.myname);继承属性

继承属性

如果访问者的属性是被继承的,它的 get 和set 方法会在子对象的属性被访问或者修改时被调用。如果这些方法用一个变量存值,该值会被所有对象共享。

function myclass() {
} var value;
Object.defineProperty(myclass.prototype, "x", {
get() {
return value;
},
set(x) {
value = x;
}
}); var a = new myclass();
var b = new myclass();
a.x = 1;
console.log(b.x); // 1 这可以通过将值存储在另一个属性中固定。在 get 和 set 方法中,this 指向某个被访问和修改属性的对象。 function myclass() {
} Object.defineProperty(myclass.prototype, "x", {
get() {
return this.stored_x;
},
set(x) {
this.stored_x = x;
}
}); var a = new myclass();
var b = new myclass();
a.x = 1;
console.log(b.x); // undefined
不像访问者属性,值属性始终在对象自身上设置,而不是一个原型。然而,如果一个不可写的属性被继承,它仍然可以防止修改对象的属性。
function myclass() {
} myclass.prototype.x = 1;
Object.defineProperty(myclass.prototype, "y", {
writable: false,
value: 1
}); var a = new myclass();
a.x = 2;
console.log(a.x); // 2
console.log(myclass.prototype.x); // 1
a.y = 2; // Ignored, throws in strict mode
console.log(a.y); // 1
console.log(myclass.prototype.y); // 1

Object.defineProperty使用技巧的更多相关文章

  1. javascript之Object.defineProperty的奥妙

    直切主题 今天遇到一个这样的功能: 写一个函数,该函数传递两个参数,第一个参数为返回对象的总数据量,第二个参数为初始化对象的数据.如: var o = obj (4, {name: 'xu', age ...

  2. Object.defineproperty实现数据和视图的联动

    Object.defineproperty语法 var o = {}; // 创建一个新对象 // Example of an object property added with definePro ...

  3. Vue 双向数据绑定原理分析 以及 Object.defineproperty语法

    第三方精简版实现 https://github.com/luobotang/simply-vue Object.defineProperty 学习,打开控制台分别输入以下内容调试结果 userInfo ...

  4. Object.defineProperty vs __defineGetter__ vs normal

    Testing in Chrome 31.0.1650.63 32-bit on Windows Server 2008 R2 / 7 64-bit Test Ops/sec Object.defin ...

  5. Object.defineProperty

    属性类型ECMA-262第5版在定义只有内部才用的特性(attribute)时,描述了属性(property)的各种特征.ECMA-262定义这些特性是为了实现JavaScript引擎用的,因此在Ja ...

  6. Object.defineproperty实现数据和视图的联动 ------是不是就是 Angular 模型和视图的同步的实现方式???

    参考:http://www.cnblogs.com/oceanxing/p/3938443.html https://developer.mozilla.org/zh-CN/docs/Web/Java ...

  7. 20+行代码使用es5 Object.defineProperty 实现简单的watch功能

    /** * 一个简单的demo 帮助理解defineProperty,只对Object类型参数有效 */ $watch=function(myObject,callback){ function in ...

  8. Object.defineProperty()方法的用法详解

    Object.defineProperty()函数是给对象设置属性的. Object.defineProperty(object, propertyname, descriptor); 一共有三个参数 ...

  9. 理解Object.defineProperty()

    理解Object.defineProperty() Object.defineProperty() 方法直接在一个对象上定义一个新属性,或者修改一个已经存在的属性, 并返回这个对象. 基本语法:Obj ...

随机推荐

  1. 爬虫防封IP

    当抓取数据逐渐增大时,服务器的负荷会加大,会直接封掉来访IP: 采取措施: 1.创建请求头部信息: headers = {'User-Agent': 'Mozilla/5.0 (Windows NT ...

  2. Codeforces - tag::data structures 大合集 [占坑 25 / 0x3f3f3f3f]

    371D 小盘子不断嵌套与大盘子,最后与地面相连,往里面灌水,溢出部分会往下面流,求每次操作时当前的盘子的容量 其实这道题是期末考前就做好了的.. 链式结构考虑并查集,然后没了(求大佬解释第一个T的点 ...

  3. linux 安装python

    wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tgz #下载安装包 tar zxvf Python-3.6.0.tgz #解压 . ...

  4. oracle--块信息深入解析

    一,创建 Data Block是数据库中最小的I/O单元 01,建立一个新的表空间 查看默认表空间位置 select TABLESPACE_NAME,FILE_NAME from dba_data_f ...

  5. 使用virtualbox虚拟安装macos

    需要工具: 虚拟机virtualbox:https://www.virtualbox.org/ empireEFIv1085.iso启动文件:http://yunpan.cn/c6UDGwL6wJm6 ...

  6. less变量插值

    在使用less的过程中,我在background的中引用图片路径,希望先确定一个baseurl,然后再在url中使用拼接字符串的方式拼接,尝试多次,失败. 实际上less的变量插值是有自己的一套规则的 ...

  7. how to be an efficient man

    "This Monday I was invited to do a presentation on this Friday, and today is Friday. I am going ...

  8. 【lua】LWT HttpdModule

    要使用httpd模块,需要在脚本开头添加: require "httpd" httpd.pairs(apr_table) 用以遍历apr_table for key, value ...

  9. Struts2入门介绍(二)

    一.Struts执行过程的分析. 当我们在浏览器中输入了网址http://127.0.0.1:8080/Struts2_01/hello.action的时候,Struts2做了如下过程: 1.Stru ...

  10. python风味之list创建

    单重for循环 >>> [x * x for x in xrange(10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 单重for循环+if条件 & ...