Class

//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的使用代码。

  1. function Car(){
  2. }

  3. Car.prototype.material = "steel";

  4. var car1 = new Car();
  5. var car2 = new Car();

  6. document.write(car1.material);  //prints "steel" 
  7. document.write(car2.material);  //prints "steel" 

  8. //car1.prototype.material = "iron" //compile error:car1.prototype is undefined
  9. car1.material = "iron";

  10. document.write(car1.material);  //prints "iron"
  11. document.write(car2.material);  //prints "steel" 
  12. document.write(Car.prototype.material); //prints "steel"

  13. Car.prototype.material = "wood";
  14. var car3 = new Car();
  15. document.write(car1.material);  //prints "iron"
  16. document.write(car2.material ); //prints "wood"
  17. document.write(car3.material ); //prints "wood"
  18. document.write(Car.prototype.material); //prints "wood"

分析该段代码前,需要明确两个概念:对象的直属属性和继承属性。直接在构造函数中通过this.someproperty = xxx这种形式定义的someproperty属性叫做对象的直属属性,而通过如上第4行代码那样Car.prototype.material = "steel";这种形式定义的material属性叫做继承属性。由上面这段代码,我们可以总结出prototype属性的如下特点:

 

  1. prototype是function下的属性(其实任意object都拥有该属性,function是对象的一种)
  2. prototype属性的值是一个对象,因此可任意添加子属性(line 4)
  3. 类的实例可以直接通过"."来直接获取prototype下的任意子属性(line 9)
  4. 所有以此function作为构造函数创建的类实例共用prototype中的属性及值(ling 9,10)
  5. 类的实例没有prototype属性(line 12)
  6. 可以直接通过 "实例.属性 = xxx" 的方式修改继承属性,修改后的值将覆盖继承自prototype的属性,但此修改不影响prototype本身,也不影响其它类实例(line 15,16,17)
  7. 继承属性修改后,该属性就成为类实例的直属属性
  8. 可以直接修改prototype的属性值,此改变将作用于此类下的所有实例,但无法改变直属属性值(极晚绑定line 21-24)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值