本文详细介绍 ECMAScript 5 引入的 Object.create() 方法,用于指定原型创建对象。重点解析第二个参数 propertiesObject 中数据属性(writable、configurable、enumerable、value)与访问器属性(get、set)的配置方式,并通过代码示例展示其实际用法与输出结果。
Object.create() 方法概述
Object.create(proto [, propertiesObject ]) 是 ECMAScript 5 标准中提出的一种新型对象创建机制。该方法接收两个参数:第一个参数 proto 指定新对象的原型链来源,若无需继承特定原型,可传入 null;第二个参数 propertiesObject 用于定义对象的属性描述符,此参数为可选。例如:
原型继承示例
function Car (desc) {
this.desc = desc;
this.color = "red";
}
Car.prototype = {
getInfo: function() {
return 'A ' + this.color + ' ' + this.desc + '.';
}
};
//instantiate object using the constructor function
var car = Object.create(Car.prototype);
car.color = "blue";
alert(car.getInfo());
运行上述代码后的输出结果为:A blue undefined.
属性描述符详解
1、propertiesObject 参数的详细解释:各项属性默认值均为 false。
- writable:定义属性值是否可被任意修改。
- configurable:定义属性是否可被删除,以及其配置(如 writable、enumerable)是否可被修改。
- enumerable:定义属性是否可通过 for...in 循环枚举。
- value:定义属性的实际存储值。
2、访问器属性配置如下:
- get():定义获取属性值时的行为。
- set():定义设置属性值时的行为。
完整代码示例与输出
3、示例:通过具体代码示例可以直接了解其使用方法。
<!DOCTYPE html>
<html>
<head>
<title>yupeng's document </title>
<meta charset="utf-8"/>
</head>
<body>
<script type="text/javascript">
var obj = {
a:function(){
console.log(100)
},
b:function(){
console.log(200)
},
c:function(){
console.log(300)
}
}
var newObj = {};
newObj = Object.create(obj,{
t1:{
value:'yupeng',
writable:true
},
bar: {
configurable: false,
get: function() { return bar; },
set: function(value) { bar=value }
}
})
console.log(newObj.a());
console.log(newObj.t1);
newObj.t1='yupeng1'
console.log(newObj.t1);
newObj.bar=201;
console.log(newObj.bar)
function Parent() { }
var parent = new Parent();
var child = Object.create(parent, {
dataDescriptor: {
value: "This property uses this string as its value.",
writable: true,
enumerable: true
},
accessorDescriptor: {
get: function () { return "I am returning: " + accessorDescriptor; },
set: function (val) { accessorDescriptor = val; },
configurable: true
}
});
child.accessorDescriptor = 'YUPENG';
console.log(child.accessorDescriptor);
var Car2 = function(){
this.name = 'aaaaaa'
} //this is an empty object, like {}
Car2.prototype = {
getInfo: function() {
return 'A ' + this.color + ' ' + this.desc + '.';
}
};
var newCar = new Car2();
var car2 = Object.create(newCar, {
//value properties
color: { writable: true, configurable:true, value: 'red' },
//concrete desc value
rawDesc: { writable: true, configurable:true, value: 'Porsche boxter' },
// data properties (assigned using getters and setters)
desc: {
configurable:true,
get: function () { return this.rawDesc.toUpperCase(); },
set: function (value) { this.rawDesc = value.toLowerCase(); }
}
});
car2.color = 'blue';
console.log(car2.getInfo());
car2.desc = "XXXXXXXX";
console.log(car2.getInfo());
console.log(car2.name);
</script>
</body>
</html>
代码执行后的输出结果依次为: 100 yupeng yupeng1 201 I am returning: YUPENG A blue PORSCHE BOXTER. A blue XXXXXXXX. aaaaaa
以上是对 JavaScript 中 Object.create() 这一新型对象创建方式的详细介绍,希望对读者的学习有所帮助。