js prototype

/** obsolete syntax **/    
var Person = Class.create();    //
通过 Class.create 方法创建空类    
Person.prototype = {               //
把方法定义到 prototype 中,注意,是通过 initalize 方法初始化类的属性    
  initialize: function(name) {    
    this.name = name;    
  },    
  say: function(message) {    
    return this.name + ': ' + message;    
  }    
};    
  
var guy = new Person('Miro');    
guy.say('hi');    
// -> "Miro: hi"    
                                            //prototype
中的继承方式:    
var Pirate = Class.create();    //
建立空类;    
// inherit from Person class:    
Pirate.prototype = Object.extend(new Person(), {    //
先实例化超类,再把超类中的方法复制到子类中去,    
  // redefine the speak method                               //
注意,实际上 prototype 类定义机制中并没有直接定义    
say: function(message) {                                       //
类的属性而是通过 intilize 方法,而且所有的方法都    
    return this.name + ': ' + message + ', yarr!';      //
之直接定义在 prototype 中,所以直接用原型链方式    
  }                                                                        //
继承超类的所有方法不会产生问题。    
});    
  
var john = new Pirate('Long John');    
john.say('ahoy matey');    
// -> "Long John: ahoy matey, yarr!"  
/** obsolete syntax **/ 
var Person = Class.create();    //
通过 Class.create 方法创建空类
Person.prototype = {               //
把方法定义到 prototype 中,注意,是通过 initalize 方法初始化类的属性
  initialize: function(name) { 
    this.name = name; 
  }, 
  say: function(message) { 
    return this.name + ': ' + message; 
  } 
}; 
var guy = new Person('Miro'); 
guy.say('hi'); 
// -> "Miro: hi" 
                                            //prototype
中的继承方式:
var Pirate = Class.create();    //
建立空类;
// inherit from Person class: 
Pirate.prototype = Object.extend(new Person(), {    //
先实例化超类,再把超类中的方法复制到子类中去,
  // redefine the speak method                               //
注意,实际上 prototype 类定义机制中并没有直接定义
say: function(message) {                                       //
类的属性而是通过 intilize 方法,而且所有的方法都
    return this.name + ': ' + message + ', yarr!';      //
之直接定义在 prototype 中,所以直接用原型链方式
  }                                                                        //
继承超类的所有方法不会产生问题。
}); 
var john = new Pirate('Long John'); 
john.say('ahoy matey'); 
// -> "Long John: ahoy matey, yarr!"

来看一下Class.create 方法的实现代码

var Class = {   
  create: function() {   
    return function() {                                          //
实际上把所有的属性定义到 intiliaze 方法(实际上是一个类)中,    
      this.initialize.apply(this, arguments);              //
然后通过对象冒充方式继承该类    
    }   
  }   
}             

可以从prototype 的例子充分体会到通过对象冒充和原型链类继承的差别,一般来说属性需用对象冒充方式继承,方法需用原型链方式继承。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值