日期:2014-05-16 浏览次数:20435 次
三.继承
this.prototype = {constructor : this};
??? 新函数对象被赋予一个 prototype 对象,该对象又包含一个 constructor 属性。而这个constructor属性的值即为该新函数自身. 因为Javascript 语言并没有提供一种方法去确定哪个函数作为构造器。所以每个函数都会得到一个 prototype 对象。 大多数情况下,constructor 属性没什么用,重要的是prototype 对象.Function.method("new", function(){
       //创建一个继承自身原型的对象
     var that = Object.beget(this.prototype);
       //调用构造器函数,绑定 this 到新对象上
     var other = this.apply(that,arguments);
       //如果它的返回值不是一个对象,则返回新对象
     return (typeof other === 'object' && other) || that;
}
?由上可知,我们可以定义一个构造器函数,并对其原型进行扩展.var Mammal = function(name){ // 由约定可知,构造器函数使用大写开头
	this.name = name;
};
Mammal.prototype.get_name = function(){
	return this.name;
};
Mammal.prototype.says = function(){
	return this.saying || "";
};
var myMammal = new Mammal("Herb the Mammal");
var name = myMammal.get_name();
document.writeln(name);
var Cat = function(name){
	this.name = name;
	this.saying = "meow";
};
// 替换Cat.prototype,使其"继承" Mannal
Cat.prototype = new Mammal();
Cat.prototype.purr = function(n){
	var i,s = "";
	for(i = 0 ; i < n ; i ++){
		if(s){
			s+="-";
		}
		s += "r";
	}
	return s;
};
// 覆盖原型链中的get_name()
Cat.prototype.get_name = function(){
	return this.says() + " " + this.name + " " + this.says();
};
var myCat = new Cat("Henrietta");
document.writeln(myCat.says()); // meow
document.writeln(myCat.purr(5)); // r-r-r-r-r
document.writeln(myCat.get_name()); // meow Henrietta meow
??? 伪类模式的本意是模拟OO语言中的继承,向面向对象靠拢,但它看起来显得格格不入。下面可以通过一些辅助方法来隐藏一些丑陋的细节.Function.method("inherits",function(Parent){
	this.prototype = new Parent();
	return this;
});
var Dog = function(name){
	this.name = name;
	this.saying = "wanwan";
}.inherits(Mammal).method("purr",function(n){
	var i,s = "";
	for(i = 0 ; i < n ; i ++){
		if(s){
			s+="-";
		}
		s += "w";
	}
	return s;
}).method("get_name",function(){
	return this.says() + " " + this.name +" " + this.says();
});
var myDog = new Dog("Kiten");
document.writeln(myDog.says()); // wanwan
document.writeln(myDog.purr(5)); // w-w-w-w-w
document.writeln(myDog.get_name()); // wanwan Kiten wanwan
?// 我们先使用字面变量去构造一个有用的对象:
var myMammal = {
	name : "Herb the Mammal",
	get_name : function(){
		return this.name;
	},
	says : function(){
		return this.saying || "";
	}
};
// 接下来我们可以使用 beget 方法构造出更多的实例,之后对实例进行定制。
var myCat = Object.beget(myMammal);
myCat.name = "Henrietta";
myCat.saying = "meow";
myCat.purr = function(n){
	var i,s="";
	for(i = 0 ; i < n ; i ++){
		if(s){
			s+="-";
		}
		s+="s";
	}
	return s;
};
myCat.get_name = function(){
	return this.says + " " + this.name + " " + this.says;
};
?这是一种 “差异化继承”. 通过定制该新对象,我们指明了它与其基类对象的区别.