/** 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 的例子充分体会到通过对象冒充和原型链类继承的差别,一般来说属性需用对象冒充方式继承,方法需用原型链方式继承。