javascript:inheritance(1)

伪类

//构造器调用模式
var Mammal = function (name)
{
this.name = name;
};
Mammal.prototype.get_name
= function()
{
return this.name;
};
Mammal.prototype.says
= function ()
{
return this.saying || '';
};
var Cat = function(name)
{
this.name = name;
this.saying = 'meow';
};
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;
};
Cat.prototype.get_name
= function()
{
return this.says() + ' ' + this.name + ' ' + this.says();
};

var myCat = new Cat('Henrietta');
var says = myCat.says();
var purr = myCat.purr(5);
var name = myCat.get_name();

//上面的伪类模式看起来很奇怪,我们可以隐藏一些丑陋的细节。
//使用method方法定义一个inherits方法来实现

Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
Function.method(
'inherits', function(Parent){
this.prototype = new Parent();
return this;
});
var Cat = function(name)
{
this.name = name;
this.saying = 'meow';
}.inherits(Mammal).method(
'purr',function(n){
var i, s = '';
for(i = 0; i < n; i ++)
{
if(s)
{
s
+= '-';
}
s
+= 'r';
}
return s;
}).method(
'get_name', function(){
return this.says() + ' ' + this.name + ' ' + this.says();
});

//以上代码有类似于“类”的构造器函数,但是它没有私有环境,所有属性都是公开的。无法访问父类的方法。
//而且如果调用的时候没有用new,那么this将被绑定到全局对象上,所以不但没有扩充新对象,反而破坏了全局变量。

原文地址:https://www.cnblogs.com/RitaRichard/p/2111926.html