创建一个拥有指定原型和若干个指定属性的对象.
Method of Object | |
|---|---|
| Implemented in | JavaScript 1.8.5 |
| ECMAScript Edition | ECMAScript 5th Edition |
Object.create(proto [, propertiesObject ])
如果proto参数的值不是null或者对象值,则会TypeError异常.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48 |
var
o;// 创建一个原型为null的空对象o = Object.create(null);o = {};// 以字面量方式创建的空对象就相当于:o = Object.create(Object.prototype);o = Object.create(Object.prototype, { // foo会成为所创建对象的数据属性 foo: { writable:true, configurable:true, value: "hello"
}, // bar会成为所创建对象的访问器属性 bar: { configurable: false, get: function() { return
10 }, set: function(value) { console.log("Setting `o.bar` to", value) }}})function
Constructor(){}o = new
Constructor();// 上面的一句就相当于:o = Object.create(Constructor.prototype);// 当然,如果在Constructor函数中有一些初始化代码,Object.create不能执行那些代码// 创建一个以另一个空对象为原型,且拥有一个属性p的对象o = Object.create({}, { p: { value: 42 } })// 省略了的属性特性默认为false,所以属性p是不可写,不可枚举,不可配置的:o.p = 24o.p//42o.q = 12for
(var
prop in
o) { console.log(prop)}//"q"delete
o.p//false//创建一个可写的,可枚举的,可配置的属性po2 = Object.create({}, { p: { value: 42, writable: true, enumerable: true, configurable: true
} }); |
|
1 |
|
下面的例子演示了如何使用Object.create来实现单继承.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 |
//Shape - superclassfunction
Shape() { this.x = 0; this.y = 0;}Shape.prototype.move = function(x, y) { this.x += x; this.y += y; console.info("Shape moved.");};// Rectangle - subclassfunction
Rectangle() { Shape.call(this); //call super constructor.}Rectangle.prototype = Object.create(Shape.prototype);var
rect = new
Rectangle();rect instanceof
Rectangle //true.rect instanceof
Shape //true.rect.move(); //Outputs, "Shape moved." |
|
1 |
|
如果你希望能继承到多个对象,则可以使用混入的方式.
|
1
2
3
4
5
6
7
8
9
10
11 |
function
MyClass() { SuperClass.call(this); OtherSuperClass.call(this);}MyClass.prototype = Object.create(SuperClass.prototype); //inheritmixin(MyClass.prototype, OtherSuperClass.prototype); //mixinMyClass.prototype.myMethod = function() { // do a thing}; |
mixin函数会把超类原型上的函数拷贝到子类原型上,这里mixin函数没有给出,需要由你实现.
|
1
2
3
4
5
6
7
8
9
10 |
if
(!Object.create) { Object.create = function
(o) { if
(arguments.length > 1) { throw
new
Error(‘Object.create implementation only accepts the first parameter.‘); } function
F() {} F.prototype = o; return
new
F(); };} |
|
1 |
|
这个polyfill只实现了创建一个指定原型的对象的功能,而不能同时添加特定的属性,也就是没有实现原生的Object.create函数中的第二个参数.
原文:http://www.cnblogs.com/mliudong/p/3533958.html