//constructor
function Car(color, title){
this.color = color;
this.title = title;
this.start = start;
}
var car1 = new Car("red", "BMW");
var car2 = new Car("yellow", "VOIS");
原型 prototype
在”构造函数+原型法“中,我们对于类的method期待得到的效果是:1、仅是类的method而不是全局的 2、只在类被定义时创建一个method实例,然后被所有类的实例共用。由这两个目标,我们很容易想到高级面向对象语言Java的private static变量的特点。JavaScript没有为我们提供这么简单的符号来实现这个复杂功能,但是却有一个属性可以帮我们仿造出这种效果:prototype。我们先来看几段prototype的使用代码。
- function Car(){
- }
- Car.prototype.material = "steel";
- var car1 = new Car();
- var car2 = new Car();
- document.write(car1.material); //prints "steel"
- document.write(car2.material); //prints "steel"
- //car1.prototype.material = "iron" //compile error:car1.prototype is undefined
- car1.material = "iron";
- document.write(car1.material); //prints "iron"
- document.write(car2.material); //prints "steel"
- document.write(Car.prototype.material); //prints "steel"
- Car.prototype.material = "wood";
- var car3 = new Car();
- document.write(car1.material); //prints "iron"
- document.write(car2.material ); //prints "wood"
- document.write(car3.material ); //prints "wood"
- document.write(Car.prototype.material); //prints "wood"
分析该段代码前,需要明确两个概念:对象的直属属性和继承属性。直接在构造函数中通过this.someproperty = xxx这种形式定义的someproperty属性叫做对象的直属属性,而通过如上第4行代码那样Car.prototype.material = "steel";这种形式定义的material属性叫做继承属性。由上面这段代码,我们可以总结出prototype属性的如下特点:
- prototype是function下的属性(其实任意object都拥有该属性,function是对象的一种)
- prototype属性的值是一个对象,因此可任意添加子属性(line 4)
- 类的实例可以直接通过"."来直接获取prototype下的任意子属性(line 9)
- 所有以此function作为构造函数创建的类实例共用prototype中的属性及值(ling 9,10)
- 类的实例没有prototype属性(line 12)
- 可以直接通过 "实例.属性 = xxx" 的方式修改继承属性,修改后的值将覆盖继承自prototype的属性,但此修改不影响prototype本身,也不影响其它类实例(line 15,16,17)
- 继承属性修改后,该属性就成为类实例的直属属性
- 可以直接修改prototype的属性值,此改变将作用于此类下的所有实例,但无法改变直属属性值(极晚绑定line 21-24)