创建一个类,从另一个类扩展并调用父方法

时间:2012-11-21 19:59:46

标签: javascript oop inheritance superclass

首先,我从coffeescript网站上获取了动物示例。

我想在javascript中模拟下一步:

  • 仅限公共方法
  • 仅限私人方法和变量
  • 继承
  • 从超类中调用方法

我认为这种方法可以创建它,但是当我尝试从父类中获取move方法时,它总是返回自身。我做错了什么?

顺便说一句。哪些是实现目标的最佳实践?是对的我在做什么?

var Animal = (function() {
    function Animal() {}

    var _private = {};
    var _public = {
        move: function() {
            console.log('Can move');
        }
    };

    Animal.prototype = _public;
    Animal.prototype.constructor = Animal;
    return Animal;
})();

var Snake = (function(_super) {
    function Snake() {}

    var _private = {};
    var _public = {
        move: function() {
            console.log(Snake._super_.move);
            console.log('Slithering');
        }
    };

    Snake.prototype = _super.prototype;
    Snake._super_ = _super.prototype;
    for(var method in _public) {
        if(Object.prototype.toString.call(_public[method]) === '[object Function]') {
            Snake.prototype[method] = _public[method];
        }
    }
    return Snake;
})(Animal);

var s = new Snake;
s.move();

2 个答案:

答案 0 :(得分:3)

在我看来,这是一个写得很好的代码,只有一个小错误。

我认为你的指针有点划线,试试这个:

<script>
var Animal = (function () {
    function Animal() { }

    var _private = {};
    var _public = {
        move: function () {
            console.log('Can move');
            //this just returns a string to show which method was called
            //inside of the child's move function's console.log
            return "super move called";
        }
    };

    Animal.prototype = _public;
    Animal.prototype.constructor = Animal;
    return Animal;
})();

var Snake = (function (_super) {
    function Snake() { }

    var _private = {};
    var _public = {
        move: function () {
            console.log(Snake._super_.move());//Now we can call super's move
            console.log('Slithering');
        }
    };

    //This created the circular reference where Snake._super_ was pointing to
    //Snake.prototype which was causing the error
    //Snake.prototype = _super.prototype;
    Snake._super_ = _super.prototype;

    for (var method in _public) {
        if (Object.prototype.toString.call(_public[method]) === '[object Function]') {
            Snake.prototype[method] = _public[method];
        }
    }
    return Snake;
})(Animal);

var s = new Snake;
s.move();//now this outputs "Can move", "super move called", "Slithering"
</script>

答案 1 :(得分:3)

如果您要求最佳实践,我会说准备好在网上找到解决方案。我更喜欢这个:http://canjs.us/#can_construct

关于你的方法的一些注意事项:

  1. 它不可重复使用。您必须为每个类编写相同的代码。至少你应该提取for循环以使这段代码可重用。
  2. 您需要检查_public.hasOwnProperty(method)以使代码更强大。
  3. toStringvalueOf方法需要特殊处理,因为它们在IE&lt; 9中不可枚举。
  4. Snake.prototype = _super.prototype;是一场彻底的灾难。因为你的超级班级将拥有所有孩子的方法。

    var F = function(){};
    F.prototype = _super.prototype;
    Snake.prototype = new F();
    Snake.prototype.constructor = Snake;