Object的方法

时间:2023-03-09 16:32:56
Object的方法

1、Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。 ES2015引入的

,且可用polyfilled。要支持旧浏览器的话,可用使用jQuery.extend或者_.assign()。

2、Object.create() 方法会使用指定的原型对象及其属性去创建一个新的对象。

语法:

Object.create(proto[, propertiesObject])

实现类式继承

function MyClass() {
SuperClass.call(this);
OtherSuperClass.call(this);
} // 继承一个类
MyClass.prototype = Object.create(SuperClass.prototype);
// 混合其它
Object.assign(MyClass.prototype, OtherSuperClass.prototype);
// 重新指定constructor
MyClass.prototype.constructor = MyClass; MyClass.prototype.myMethod = function() {
// do a thing
};  

使用 Object.create 的 propertyObject参数

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 = 24
o.p
//42 o.q = 12
for (var prop in o) {
console.log(prop)
}
//"q" delete o.p
//false //创建一个可写的,可枚举的,可配置的属性p
o2 = Object.create({}, {
p: {
value: 42,
writable: true,
enumerable: true,
configurable: true
}
});

  

Polyfill

这个 polyfill 涵盖了主要的应用场景,它创建一个已经选择了原型的新对象,但没有把第二个参数考虑在内。

请注意,尽管在 ES5 中 Object.create支持设置为[[Prototype]]null,但因为那些ECMAScript5以前版本限制,此 polyfill 无法支持该特性。

if (typeof Object.create !== "function") {
Object.create = function (proto, propertiesObject) {
if (typeof proto !== 'object' && typeof proto !== 'function') {
throw new TypeError('Object prototype may only be an Object: ' + proto);
} else if (proto === null) {
throw new Error("This browser's implementation of Object.create is a shim and doesn't support 'null' as the first argument.");
} if (typeof propertiesObject != 'undefined') throw new Error("This browser's implementation of Object.create is a shim and doesn't support a second argument."); function F() {}
F.prototype = proto; return new F();
};
}

_.assign

js:https://lodash.com/vendor/cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js

function Foo() {
this.a = 1;
} function Bar() {
this.c = 3;
} Foo.prototype.b = 2;
Bar.prototype.d = 4; _.assign({ 'a': 0 }, new Foo, new Bar);
// => { 'a': 1, 'c': 3 }

_.assignIn

function Foo() {
this.a = 1;
} function Bar() {
this.c = 3;
} Foo.prototype.b = 2;
Bar.prototype.d = 4; _.assignIn({ 'a': 0 }, new Foo, new Bar);
// => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }