`
chengyong
  • 浏览: 28810 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

用原型实现javascript中的继承

 
阅读更多

做了三年php,因为工作需要,目前要转javascript。前段时间去面试的时候遇到在javascript中实现继承的题,当时答的也不好,回来找了些资料,做个整理。

 

《javascript语言精粹》一书是提到了一点,使用伪类的方式来实现继承,大概就是构造一个伪类继承自基类,然后再定义它的constructor函数,并替换它的prototype为一个基类的实例来实现,但是这样就会有很多"无谓的"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();

var Cat = function(name){
    this.name = name;
    this.saying = 'meow';
};

// 替换Cat.prototype为一个新的Mammal实例
Cat.prototype = new Mammal();

// 扩充原型对象,增加方法
Cat.prototype.eat = function(){
    // other
};

Cat.prototype.get_name = function(){
    // other
};

var myCat = new Cat('mimi');
var says = myCat.says(); // 'meow'
var name = myCat.get_name();
myCat.eat();

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics