6.2.3 原型模式
我们创建的每个函数都有一个prototype(原型)属性,这个属性是一个指针,指向一个对象,而这个对象的用途是
包含可以由特定类型的所有实例共享的属性和方法。如果按照字面意思来理解,那么prototype 就是通过调用
构造函数而创建的那个对象实例的原型对象。
使用原型对象的好处是可以让所有对象实例共享它所包含的属性和方法。
换句话说,不必在构造函数中定义对象实例的信息,而是可以将这些信息直接添加到原型对象中,如下面的例子所示。
<!DOCTYPE html>
<html>
<head>
<title>Prototype Pattern Example</title>
<script type="text/javascript">
function Person(){
}
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function(){
alert(this.name);
};
var person1 = new Person();
person1.sayName(); //"Nicholas"
var person2 = new Person();
person2.sayName(); //"Nicholas"
alert(person1.sayName == person2.sayName); //true
alert(Person.prototype.isPrototypeOf(person1)); //true
alert(Person.prototype.isPrototypeOf(person2)); //true
//only works if Object.getPrototypeOf() is available
if (Object.getPrototypeOf){
alert(Object.getPrototypeOf(person1) == Person.prototype); //true
alert(Object.getPrototypeOf(person1).name); //"Nicholas"
}
</script>
</head>
<body>
</body>
</html>
在此,我们将sayName()方法和所有属性直接添加到了Person 的prototype 属性中,构造函数变成了空函数。
即使如此,也仍然可以通过调用构造函数来创建新对象,而且新对象还会具有相同的属性和方法。
但与构造函数模式不同的是,新对象的这些属性和方法是由所有实例共享的。
换句话说,person1 和person2 访问的都是同一组属性和同一个sayName()函数。
要理解原型模式的工作原理,必须先理解ECMAScript 中原型对象的性质。
1. 理解原型对象
无论什么时候,只要创建了一个新函数,就会根据一组特定的规则为该函数创建一个prototype属性,
这个属性指向函数的原型对象。在默认情况下,所有原型对象都会自动获得一个constructor(构造函数)属性,
这个属性包含一个指向prototype 属性所在函数的指针。就拿前面的例子来说,
Person.prototype. constructor 指向Person。而通过这个构造函数,我们还可继续为原型对象添加其他属性和方法。
------------------------------------------------------------------------------------------------------------------------------------------------------
创建了自定义的构造函数之后,其原型对象默认只会取得constructor 属性;至于其他方法,则都是从Object 继承而来的。
当调用构造函数创建一个新实例后,该实例的内部将包含一个指针(内部属性),指向构造函数的原型对象。
ECMA-262 第5 版中管这个指针叫[[Prototype]]。虽然在脚本中没有标准的方式访问[[Prototype]],
但Firefox、Safari 和Chrome 在每个对象上都支持一个属性__proto__;
而在其他实现中,这个属性对脚本则是完全不可见的。不过,要明确的真正重要的一点就是,
这个连接存在于实例与构造函数的原型对象之间,而不是存在于实例与构造函数之间。
------------------------------------------------------------------------------------------------------------------------------------------------------
以前面使用Person 构造函数和Person.prototype 创建实例的代码为例,图6-1 展示了各个对象之间的关系。
图6-1 展示了Person 构造函数、Person 的原型属性以及Person 现有的两个实例之间的关系。
在此,Person.prototype 指向了原型对象,而Person.prototype.constructor 又指回了Person。
原型对象中除了包含constructor 属性之外,还包括后来添加的其他属性。Person 的每个实例——
person1 和person2 都包含一个内部属性,该属性仅仅指向了Person.prototype;
换句话说,它们与构造函数没有直接的关系。此外,要格外注意的是,虽然这两个实例都不包含属性和方法,
但我们却可以调用person1.sayName()。这是通过查找对象属性的过程来实现的。
------------------------------------------------------------------------------------------------------------------------------------------------------
虽然在所有实现中都无法访问到[[Prototype]],但可以通过isPrototypeOf()方法来确定对象之间是否存在这种关系。
从本质上讲,如果[[Prototype]]指向调用isPrototypeOf()方法的对象(Person.prototype),那么这个方法就返回true,如下所示:
alert(Person.prototype.isPrototypeOf(person1)); //true
alert(Person.prototype.isPrototypeOf(person2)); //true
这里,我们用原型对象的isPrototypeOf()方法测试了person1 和person2。因为它们内部都有一个指向Person.prototype 的指针,
因此都返回了true。
ECMAScript 5 增加了一个新方法,叫Object.getPrototypeOf(),在所有支持的实现中,这个方法返回[[Prototype]]的值。例如:
alert(Object.getPrototypeOf(person1) == Person.prototype); //true
alert(Object.getPrototypeOf(person1).name); //"Nicholas"
这里的第一行代码只是确定Object.getPrototypeOf()返回的对象实际就是这个对象的原型。
第二行代码取得了原型对象中name 属性的值,也就是"Nicholas"。
使用Object.getPrototypeOf()可以方便地取得一个对象的原型,而这在利用原型实现继承(本章稍后会讨论)的
情况下是非常重要的。
支持这个方法的浏览器有IE9+、Firefox 3.5+、Safari 5+、Opera 12+和Chrome。
每当代码读取某个对象的某个属性时,都会执行一次搜索,目标是具有给定名字的属性。
搜索首先从对象实例本身开始。如果在实例中找到了具有给定名字的属性,则返回该属性的值;
如果没有找到,则继续搜索指针指向的原型对象,在原型对象中查找具有给定名字的属性。
如果在原型对象中找到了这个属性,则返回该属性的值。也就是说,在我们调用person1.sayName()的时候,
会先后执行两次搜索。首先,解析器会问:“实例person1 有sayName 属性吗?”答:“没有。”
然后,它继续搜索,再问:“person1 的原型有sayName 属性吗?”答:“有。”于是,
它就读取那个保存在原型对象中的函数。当我们调用person2.sayName()时,将会重现相同的搜索过程,
得到相同的结果。而这正是多个对象实例共享原型所保存的属性和方法的基本原理。
PS:前面提到过,原型最初只包含constructor 属性,而该属性也是共享的,因此可以通过对象实例访问。
------------------------------------------------------------------------------------------------------------------------------------------------------
虽然可以通过对象实例访问保存在原型中的值,但却不能通过对象实例重写原型中的值。如果我们
在实例中添加了一个属性,而该属性与实例原型中的一个属性同名,那我们就在实例中创建该属性,
该属性将会屏蔽原型中的那个属性。来看下面的例子。
<!DOCTYPE html>
<html>
<head>
<title>Prototype Pattern Example 2</title>
<script type="text/javascript">
function Person(){
}
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function(){
alert(this.name);
};
var person1 = new Person();
var person2 = new Person();
person1.name = "Greg";
alert(person1.name); //"Greg"——来自实例
alert(person2.name); //"Nicholas"——来自原型
</script>
</head>
<body>
</body>
</html>
在这个例子中,person1 的name 被一个新值给屏蔽了。但无论访问person1.name 还是访问person2.name 都能够正常地返回值,
即分别是"Greg"(来自对象实例)和"Nicholas"(来自原型)。
当在alert()中访问person1.name 时,需要读取它的值,因此就会在这个实例上搜索一个名为name的属性。
这个属性确实存在,于是就返回它的值而不必再搜索原型了。当以同样的方式访问person2.name 时,
并没有在实例上发现该属性,因此就会继续搜索原型,结果在那里找到了name 属性。
------------------------------------------------------------------------------------------------------------------------------------------------------
当为对象实例添加一个属性时,这个属性就会屏蔽原型对象中保存的同名属性;
换句话说,添加这个属性只会阻止我们访问原型中的那个属性,但不会修改那个属性。即使将这个属性设置为null,
也只会在实例中设置这个属性,而不会恢复其指向原型的连接。不过,使用delete 操作符则可以完全删除实例属性,
从而让我们能够重新访问原型中的属性,如下所示。
<!DOCTYPE html>
<html>
<head>
<title>Prototype Pattern Example 3</title>
<script type="text/javascript">
function Person(){
}
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function(){
alert(this.name);
};
var person1 = new Person();
var person2 = new Person();
person1.name = "Greg";
alert(person1.name); //"Greg"——来自实例
alert(person2.name); //"Nicholas"——来自原型
delete person1.name;
alert(person1.name); //"Nicholas"——来自原型
</script>
</head>
<body>
</body>
</html>
在这个修改后的例子中,我们使用delete 操作符删除了person1.name,之前它保存的"Greg"值屏蔽了同名的原型属性。
把它删除以后,就恢复了对原型中name 属性的连接。因此,接下来再调用person1.name 时,
返回的就是原型中name 属性的值了。
------------------------------------------------------------------------------------------------------------------------------------------------------
使用hasOwnProperty()方法可以检测一个属性是存在于实例中,还是存在于原型中。这个方法(不要忘了它是从Object 继承来的)
只在给定属性存在于对象实例中时,才会返回true。来看下面这个例子。
function Person(){
}
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function(){
alert(this.name);
};
var person1 = new Person();
var person2 = new Person();
alert(person1.hasOwnProperty("name")); //false
person1.name = "Greg";
alert(person1.name); //"Greg"——来自实例
alert(person1.hasOwnProperty("name")); //true
alert(person2.name); //"Nicholas"——来自原型
alert(person2.hasOwnProperty("name")); //false
delete person1.name;
alert(person1.name); //"Nicholas"——来自原型
alert(person1.hasOwnProperty("name")); //false
通过使用hasOwnProperty()方法,什么时候访问的是实例属性,什么时候访问的是原型属性就一清二楚了。
调用person1.hasOwnProperty( "name")时,只有当person1 重写name 属性后才会返回true,
因为只有这时候name 才是一个实例属性,而非原型属性。图6-2 展示了上面例子在不同情
况下的实现与原型的关系(为了简单起见,图中省略了与Person 构造函数的关系)。
PS:ECMAScript 5 的Object.getOwnPropertyDescriptor()方法只能用于实例属性,要取得原型属性的描述符,
必须直接在原型对象上调用Object.getOwnPropertyDescriptor()方法。
------------------------------------------------------------------------------------------------------------------------------------------------------------
2. 原型与in 操作符
有两种方式使用in 操作符:单独使用和在for-in 循环中使用。在单独使用时,in 操作符会在通
过对象能够访问给定属性时返回true,无论该属性存在于实例中还是原型中。看一看下面的例子。
<!DOCTYPE html>
<html>
<head>
<title>Prototype Pattern Example 4</title>
<script type="text/javascript">
function Person(){
}
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function(){
alert(this.name);
};
var person1 = new Person();
var person2 = new Person();
alert(person1.hasOwnProperty("name")); //false
alert("name" in person1); //true
person1.name = "Greg";
alert(person1.name); //"Greg" ——来自实例
alert(person1.hasOwnProperty("name")); //true
alert("name" in person1); //true
alert(person2.name); //"Nicholas" ——来自原型
alert(person2.hasOwnProperty("name")); //false
alert("name" in person2); //true
delete person1.name;
alert(person1.name); //"Nicholas" ——来自原型
alert(person1.hasOwnProperty("name")); //false
alert("name" in person1); //true
</script>
</head>
<body>
</body>
</html>
在以上代码执行的整个过程中,name 属性要么是直接在对象上访问到的,要么是通过原型访问到的。
因此,调用"name" in person1 始终都返回true,无论该属性存在于实例中还是存在于原型中。
同时使用hasOwnProperty()方法和in 操作符,就可以确定该属性到底是存在于对象中,还是存在于原型中,如下所示。
function hasPrototypeProperty(object, name){
return !object.hasOwnProperty(name) && (name in object);
}
由于in 操作符只要通过对象能够访问到属性就返回true,hasOwnProperty()只在属性存在于实例中时才返回true,
因此只要in 操作符返回true 而hasOwnProperty()返回false,就可以确定属性是原型中的属性。
下面来看一看上面定义的函数hasPrototypeProperty()的用法。
<!DOCTYPE html>
<html>
<head>
<title>Prototype Pattern Example</title>
<script type="text/javascript">
function hasPrototypeProperty(object, name){
return !object.hasOwnProperty(name) && (name in object);
}
function Person(){
}
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function(){
alert(this.name);
};
var person = new Person();
alert(hasPrototypeProperty(person, "name")); //true
person.name = "Greg";
alert(hasPrototypeProperty(person, "name")); //false
</script>
</head>
<body>
</body>
</html>
在这里,name 属性先是存在于原型中,因此hasPrototypeProperty()返回true。当在实例中重写name 属性后,
该属性就存在于实例中了,因此hasPrototypeProperty()返回false。即使原型中仍然有name 属性,
但由于现在实例中也有了这个属性,因此原型中的name 属性就用不到了。
------------------------------------------------------------------------------------------------------------------------------------------------------------
在使用for-in 循环时,返回的是所有能够通过对象访问的、可枚举的(enumerated)属性,其中
既包括存在于实例中的属性,也包括存在于原型中的属性。屏蔽了原型中不可枚举属性(即将
[[Enumerable]]标记为false 的属性)的实例属性也会在for-in 循环中返回,因为根据规定,所
有开发人员定义的属性都是可枚举的——只有在IE8 及更早版本中例外。
IE 早期版本的实现中存在一个bug,即屏蔽不可枚举属性的实例属性不会出现在for-in 循环中。
例如:
<!DOCTYPE html>
<html>
<head>
<title>Prototype Pattern Example</title>
<script type="text/javascript">
var o = {
toString : function(){
return "My Object";
}
}
for (var prop in o){
if (prop == "toString"){
alert("Found toString");
}
}
</script>
</head>
<body>
</body>
</html>
当以上代码运行时,应该会显示一个警告框,表明找到了toString()方法。这里的对象o 定义了一个名为toString()的方法,
该方法屏蔽了原型中(不可枚举)的toString()方法。在IE 中,由于其实现认为原型的toString()方法被打上了值为false 的
[[Enumerable]]标记,因此应该跳过该属性,结果我们就不会看到警告框。该bug 会影响默认不可枚举的所有属性和方法,包括:
hasOwnProperty()、propertyIsEnumerable()、toLocaleString()、toString()和valueOf()。
ECMAScript 5 也将constructor 和prototype 属性的[[Enumerable]]特性设置为false,但并不是所有浏览器都照此实现。
------------------------------------------------------------------------------------------------------------------------------------------------------------
要取得对象上所有可枚举的实例属性,可以使用ECMAScript 5 的Object.keys()方法。这个方法
接收一个对象作为参数,返回一个包含所有可枚举属性的字符串数组。例如:
<!DOCTYPE html>
<html>
<head>
<title>Object.keys() Example</title>
<script type="text/javascript">
function Person(){
}
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function(){
alert(this.name);
};
var keys = Object.keys(Person.prototype);
alert(keys); //"name,age,job,sayName"
</script>
</head>
<body>
<p>Note: this example only works in browsers that have implemented the ECMAScript 5 <code>Object.defineProperty()</code> method (IE9 and Firefox 4).</p>
</body>
</html>
这里,变量keys 中将保存一个数组,数组中是字符串"name"、"age"、"job"和"sayName"。
这个顺序也是它们在for-in 循环中出现的顺序。如果是通过Person 的实例调用,则Object.keys()
返回的数组只包含"name"和"age"这两个实例属性。
如果你想要得到所有实例属性,无论它是否可枚举,都可以使用Object.getOwnPropertyNames()方法。
<!DOCTYPE html>
<html>
<head>
<title>Object.getOwnPropertyNames() Example</title>
<script type="text/javascript">
function Person(){
}
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function(){
alert(this.name);
};
var keys = Object.getOwnPropertyNames(Person.prototype);
alert(keys); //"constructor,name,age,job,sayName"
</script>
</head>
<body>
<p>Note: this example only works in browsers that have implemented the ECMAScript 5 <code>Object.defineProperty()</code> method (IE9, Firefox 4, and Chrome 7).</p>
</body>
</html>
注意结果中包含了不可枚举的constructor 属性。Object.keys()和Object.getOwnPropertyNames()方法都可以用来替代for-in 循环。
支持这两个方法的浏览器有IE9+、Firefox 4+、Safari 5+、Opera12+和Chrome。
----------------------------------------------------------------------------------------------------------------------------------------------
3. 更简单的原型语法
读者大概注意到了,前面例子中每添加一个属性和方法就要敲一遍Person.prototype。
为减少不必要的输入,也为了从视觉上更好地封装原型的功能,更常见的做法是
用一个包含所有属性和方法的对象字面量来重写整个原型对象,如下面的例子所示。
<!DOCTYPE html>
<html>
<head>
<title>Prototype Pattern Example</title>
<script type="text/javascript">
function Person(){
}
Person.prototype = {
name : "Nicholas",
age : 29,
job: "Software Engineer",
sayName : function () {
alert(this.name);
}
};
var friend = new Person();
alert(friend instanceof Object); //true
alert(friend instanceof Person); //true
alert(friend.constructor == Person); //false
alert(friend.constructor == Object); //true
</script>
</head>
<body>
</body>
</html>
在上面的代码中,我们将Person.prototype 设置为等于一个以对象字面量形式创建的新对象。
最终结果相同,但有一个例外:constructor 属性不再指向Person 了。前面曾经介绍过,每创建一
个函数,就会同时创建它的prototype 对象,这个对象也会自动获得constructor 属性。而我们在
这里使用的语法,本质上完全重写了默认的prototype 对象,因此constructor 属性也就变成了新
对象的constructor 属性(指向Object 构造函数),不再指向Person 函数。此时,尽管instanceof
操作符还能返回正确的结果,但通过constructor 已经无法确定对象的类型了,如下所示。
var friend = new Person();
alert(friend instanceof Object); //true
alert(friend instanceof Person); //true
alert(friend.constructor == Person); //false
alert(friend.constructor == Object); //true
在此,用instanceof 操作符测试Object 和Person 仍然返回true,但constructor 属性则等于Object 而不等于Person 了。
如果constructor 的值真的很重要,可以像下面这样特意将它设置回适当的值。
<!DOCTYPE html>
<html>
<head>
<title>Prototype Pattern Example</title>
<script type="text/javascript">
function Person(){
}
Person.prototype = {
constructor : Person,
name : "Nicholas",
age : 29,
job: "Software Engineer",
sayName : function () {
alert(this.name);
}
};
var friend = new Person();
alert(friend instanceof Object); //true
alert(friend instanceof Person); //true
alert(friend.constructor == Person); //true
alert(friend.constructor == Object); //false
</script>
</head>
<body>
</body>
</html>
以上代码特意包含了一个constructor 属性,并将它的值设置为Person,从而确保了通过该属性能够访问到适当的值。
注意,以这种方式重设constructor 属性会导致它的[[Enumerable]]特性被设置为true。默认情况下,
原生的constructor 属性是不可枚举的,因此如果你使用兼容ECMAScript 5 的JavaScript 引擎,可以试一试Object.defineProperty()。
function Person(){
}
Person.prototype = {
name : "Nicholas",
age : 29,
job : "Software Engineer",
sayName : function () {
alert(this.name);
}
};
//重设构造函数,只适用于ECMAScript 5 兼容的浏览器
Object.defineProperty(Person.prototype, "constructor", {
enumerable: false,
value: Person
});
4. 原型的动态性
原型这块知识点太多,记不住,略
5. 原生对象的原型
原型这块知识点太多,记不住,略
6. 原型对象的问题
原型这块知识点太多,记不住,略