创建对象的几种方式
2020-02-23 本文已影响0人
小啊美
- 字面量式(最常用)
var person = {
name: 'xiaoming',
age: 18,
sayHello: function () {
console.log('hello', this.name)
}
}
- 调用系统的Object构造函数,创建实例对象
var person = new Object();
person.name = 'xiaoming'
person.age = 18
person.sayHello = function () {
console.log('hello', this.name)
}
- 工厂模式
function person (name, age) {
var obj = new Object()
obj.name = name
obj.age = age
obj.sayHello = function () {
console.log('hello', this.name)
}
return obj
}
var per = person('xiaoming', 18)
- 构造函数模式
function Person (name, age) {
this.name = name;
this.age = age;
this.sayHello = function () {
console.log('hello', this.name)
}
}
var per = new Person('xiaoming', 18)
per.sayHello() //输出 hello, xiaoming
与工厂模式的区别:
- 没有显式的创建对象
- 将属性和方法直接赋给了this对象
- 没有return语句
- 原型模式
function Person () {}
Person.prototype.name = 'xiaoming'
Person.prototype.age = 18
Person.prototype.sayHello = function () {
console.log('hello', this.name)
}
var per1 = new Person()
per1.sayHello() // 'hello, xiaoming'
var per2 = new Person ()
per2.sayHello() // 'hello, xiaoming'
- 组合使用构造函数模式和原型模式(应用最广泛)
function Person (name, age) {
this.name = name;
this.age = age;
}
Person.prototype = {
constructor: Person,
sayHello = function () {
console.log('hello', this.name)
}
}
var per1 = new Person()
per1.sayHello() // 'hello, xiaoming'
- 动态原型模式
function Person (name, age) {
this.name = name;
this.age = age;
if (typeof this.sayHello !== 'function') {
Person.prototype.sayHello = function () {
console.log('hello', this.name)
}
}
}
var per = new Person ('xiaoming', 18)
per.sayHello()
注意
if(){}这段代码只会在初次调用函数时才会执行。其中,if 语句检查的可以是初始化之后应该存在的任何属性或方法,不必用一大堆 if 语句检查每个属性和每个方法;只要检查其中一个即可。
- 寄生构造函数模式
基本思想:创建一个函数,该函数的作用仅仅是封装创建对象的代码,然后返回新创建的对象。
function Person (name, age) {
var o = new Object();
o.name = name;
o.age = age;
o.sayHello = function () {
console.log('hello', this.name)
}
return o;
}
var per = new Person('xiaoming', 18);
per.sayHello() // 'hello, xiaoming'
使用场景:
function CustomArray () {
var arr = new Array();
// 添加值
arr.push.apply(arr, arguments);
// 添加方法
arr.toPipedString = function () {
return this.join('|');
}
return arr;
}
var arr = new CustomArray(1,2,3,4,5)
arr.toPipedString()
- 稳妥构造函数模式
稳妥对象指的是没有公共属性,而且其方法也不引用this的对象。
稳妥构造函数遵循与寄生构造函数类似的模式,不同处为:- 新创建对象的实例方法不引用this;
2.不使用new操作符调用构造函数;
稳妥构造函数与工厂模式的不同之处为,其方法不引用this的对象
- 新创建对象的实例方法不引用this;
function Person (name, age) {
var o = new Object();
o.sayName = function () {
console.log(name);
}
return o;
}
var per = Person('xiaoming', 18);
per.sayName()
注意:变量per中保存的是一个稳妥对象,用这种模式创建的对象,只能用sayName()访问name的值。
稳妥构造函数模式提供的这种安全性,非常适合在某些安全执行环境下使用,例如:ADsafe(www.adsafe.org)和 Caja(http://code.google.com/p/google-caja/)