创建普通对象
对象字面量
var object = {
public_property: 1,
public_method: function () {
return this.public_property;
}
};
内置构造函数
var object = new Object();
object.public_property = 1;
object.public_method = function () {
return this.public_property;
};
创建对象实例
工厂模式(闭包)
function factory() {
var private_property = 1;
function private_method() {
return private_property;
}
return {
public_property: 1,
public_method: function () {
return [this.public_property, private_method()];
}
};
}
var object = factory();
构造函数
function Class() {
this.public_property = 1;
}
Class.prototype.public_method = function () {
return this.public_property;
};
var object = new Class();
Object.create = function (prototype) {
function Temp() {}
Temp.prototype = prototype;
return new Temp();
};
var object = Object.create(Class.prototype);
子类继承父类
父类修饰子类
function Parent() {
this.public_property = 1;
}
Parent.prototype.public_method = function () {
return this.public_property;
};
function Child() {
Parent.call(this);
this.public_property = 1;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.public_method = function () {
return Parent.prototype.public_method.call(this) * 2;
};
var parent = new Parent(),
child = new Child();
var outer = {};
var inner = Function.call(outer, 'return 1;');
inner();
outer();
子类修饰父类
function Child() {
var that = Object.setPrototypeOf(
new (Parent.bind.apply(null, arguments))(),
Child.prototype
);
that.public_property = 1;
return that;
}
function Child() {
var that = Object.setPrototypeOf(new Parent(...arguments), Child.prototype);
that.public_property = 1;
return that;
}