js 继承inheritance/extends

主要就是《javascript语言精粹》语言精粹中的内容

5.1伪类

Function.prototype.method = function(name,func){ this.prototype[name] = func; return this; }

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+=1){ if(s){ s += "-"; } s += "r"; } return s; } Cat.prototype.get_name = function(){ return this.says() + " " + this.name + " " + this.says(); }
var myCat = new Cat("bubu");
var says = myCat.says();
var purr = myCat.purr(5);
var name = myCat.get_name();

console.log(says , purr , 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+=1){
            if(s){
                s += "-";
            }
            s += "r";
        }
        return s;
    }).
        method("get_name",function(){
            return this.says() + " " + this.name + " " + this.says();
        });

var myCat = new Cat("bubu");
var says = myCat.says();
var purr = myCat.purr(5);
var name = myCat.get_name();

console.log(says , purr , name);

我们现在有了行为像“类”的构造器函数,但是他们可能有着令人惊讶的行为:没有私有环境;所谓的属性都是公开的。无法访问super(父类)的方法

更糟的是,使用构造器函数存在一个严重的危害。如果你在调用构造器函数时忘记在前面加上new 前缀,那么this将不会绑定到一个新对象上。更可悲的是,this将绑定到全局对象上,所以不精没有扩充新对象,反而将破坏全局变量

伪类给不熟悉js的程序员提供了便利,但是它也隐藏了该语言的真实本质。许多复杂的类层次结构产生的原因是静态类型检查的约束。js完全摆脱了那些约束。在基于类的语言中,类的继承是代码重用的唯一方式。js有更好的选择。

 

posted @ 2014-03-25 10:17  星堡a  阅读(1831)  评论(0编辑  收藏  举报