JS 创建实例对象的四种模式
需求
完成满足如下要求的函数:
- 返回一个对象
- 对象的 greeting 属性值等于 str1, name 属性值等于 str2
- 对象存在一个 sayIt 方法,该方法返回的字符串为 greeting属性值 + ‘, ‘ + name属性值
分析
js的原型系统,主要包含以下三个基本元素
属性
- prototype
- __ proto __
- constructor
原则
- 只有函数对象有
prototype
属性 - 变量的__ proto __属性返回的是它的构造函数的原型对象
- 变量的constructor属性返回的是它的构造函数
原型模式
function createModule(str1, str2) {
function Obj()
{
this.greeting = str1;
this.name = str2;
}
Obj.prototype.sayIt = function(){return this.greeting + ", " + this.name;}
return new Obj();
}
构造函数
function createModule(str1, str2) {
function Obj()
{
this.greeting = str1;
this.name = str2;
this.sayIt = function(){return this.greeting + ", " + this.name;}
}
return new Obj();
}
创建对象
function createModule(str1, str2) {
obj = new Object;
obj.greeting = str1;
obj.name = str2;
obj.sayIt = function(){return this.greeting + ", " + this.name;}
return obj;
}
字面量
function createModule(str1, str2) {
var obj =
{
greeting : str1,
name : str2,
sayIt : function(){return this.greeting + ", " + this.name;}
};
return obj;
}
小结
原型模式与构造函数方法区别在于,前者原型方法是共享的,后者构造函数内的方法则是拷贝。而Object类与字面量模式,后者只不过是简写,使用了默认包装器。
本作品采用《CC 协议》,转载必须注明作者和本文链接