在javascript中,创建对象的不同方法 (例子)
方玉
・2 分钟阅读
使用Object()构造函数:
var d = new Object();
这是创建空对象的最简单方法,我相信现在不推荐了。
使用Object.create()方法:
var a = Object.create(null);
此方法创建一个新对象,扩展作为参数传递的Prototype对象。
使用支架的合成糖
var b = {};
这等价于Object.create(null)方法,使用空Prototype作为参数。
使用函数构造函数
var Obj = function(name) {
this.name = name
}
var c = new Obj("hello");
新操作符的作用是调用函数并将这个函数设置为新的新对象,并将这个新对象的Prototype绑定到函数的Prototype ,如下所示:
function f {};
new f(a, b, c);
Would be equivalent to:
// Create a new instance using f's prototype.
var newInstance = Object.create(f.prototype)
var result;
// Call the function
result = f.call(newInstance, a, b, c),
// If the result is a non-null object, use it, otherwise use the new instance.
result && typeof result === 'object' ? result : newInstance
使用函数构造函数+Prototype :
function myObj(){};
myObj.prototype.name ="hello";
var k = new myObj();
使用ES6类语法:
class myObject {
constructor(name) {
this.name = name;
}
}
var e = new myObject("hello");
单例模式:
var l = new function(){
this.name ="hello";
}