May 27, 2017
JavaScript中创建对象的方式有很多种,每一种方式都有相应的优缺点,总结如下。
function createPerson( name ) {
var obj = new Object();
obj.name = name;
obj.getName = function () {
console.log( this.name );
};
return obj;
}
var person = createPerson('John');
function Person( name ) {
this.name = name;
this.getName = function () {
console.log( this.name );
};
}
var person1 = new Person( 'John' );
function Person( name ) {
this.name = name;
this.getName = getName;
}
function getName() {
console.log( this.name );
}
function Person( name ) {
}
Person.prototype.name = 'John';
Person.prototype.getName= function () {
console.log( this.name );
};
var person1 = new Person();
function Person( name ) {
}
Person.prototype = {
name: 'John',
getName: function () {
console.log( this.name );
}
};
var person1 = new Person();
function Person( name ) {
}
Person.prototype = {
constructor: Person,
name: 'John',
getName: function () {
console.log( this.name );
}
};
var person1 = new Person();
function Person( name ) {
this.name = name;
}
Person.prototype = {
constructor: Person,
getName: function () {
console.log( this.name );
}
};
var person1 = new Person( 'John' );
function Person( name ) {
this.name = name;
if (typeof this.getName !== 'function') {
Person.prototype.getName = function () {
console.log( this.name );
};
}
}
var person1 = new Person( 'John' );
function Person( name ) {
var obj = new Object();
obj.name = name;
obj.getName = function () {
console.log( this.name );
};
}
var person1 = new Person( 'John' );
console.log( person1 instanceof Person ); // false
console.log( person1 instanceof Object ); // true
寄生构造函数和工厂模式的区别就是实例化的时候需要new。
function person( name ) {
var obj = new Object();
obj.getName = function () {
console.log( name );
}
}
var person1 = person( 'John' );
稳妥对象,指的是没有公共属性,方法中也不引用this的对象。
与寄生构造函数模式有两点不同:
方法中不引用this
实例化不用new
优点:适合用在比较安全的环境
缺点:和工厂模式一样,无法识别对象类型
Written by ricosmall.
Github