使用prototype的Class接口继承类

时间:2017-02-14 12:21:49

标签: javascript inheritance

我正在使用原型的独立类继承:https://github.com/Jakobo/PTClass

我有以下课程:

App.hello = Class.create({

    initialize: function(args) {
        this.name = args.name
    },

    sayHello: function() {
        console.log('Hello, ' + this.name);
    },

    sayGoodbye: function() {
        console.log('Goodbye, ' + this.name);
    }

});

App.yo = Class.create(App.hello, {

    initialize: function($super) {
        $super();
    },

    sayHello: function() {
        console.log('Yo, ' + this.name);
    }

});

这意味着yo将继承hello并覆盖其sayHello方法。但也可以在其父类中调用sayGoodbye方法。

所以我称之为:

var test = new App.hello({name: 'Cameron'});
    test.sayHello();
    test.sayGoodbye();
var test2 = new App.yo({name: 'Cameron'});
    test2.sayHello();
    test2.sayGoodbye();

但是我收到了Uncaught TypeError: Cannot read property 'name' of undefinedyo的错误。

如何正确地继承我的hello课程?

1 个答案:

答案 0 :(得分:1)

问题在于yo initializer没有传递您将其传递给超类的参数:

initialize: function($super, args) { // ***
    $super(args);                    // ***
},

因此,hello initialize函数中的代码尝试从name读取args属性,但args为{{ 1}}。因此错误。

更新了工作示例:



undefined

var App = {};

App.hello = Class.create({

    initialize: function(args) {
        this.name = args.name
    },

    sayHello: function() {
        console.log('Hello, ' + this.name);
    },

    sayGoodbye: function() {
        console.log('Goodbye, ' + this.name);
    }

});

App.yo = Class.create(App.hello, {

    initialize: function($super, args) {
        $super(args);
    },

    sayHello: function() {
        console.log('Yo, ' + this.name);
    }

});

var test = new App.hello({name: 'Cameron'});
    test.sayHello();
    test.sayGoodbye();
var test2 = new App.yo({name: 'Cameron'});
    test2.sayHello();
    test2.sayGoodbye();




关于我对这个问题的评论,这里是一个不使用PrototypeJS的ES2015 +版本:



<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.3/prototype.min.js"></script>
&#13;
&#13;
&#13;

请注意,我们根本不需要为const App = {}; App.hello = class { constructor(args) { this.name = args.name } sayHello() { console.log('Hello, ' + this.name); } sayGoodbye() { console.log('Goodbye, ' + this.name); } }; App.yo = class extends App.hello { sayHello() { console.log('Yo, ' + this.name); } }; const test = new App.hello({name: 'Cameron'}); test.sayHello(); test.sayGoodbye(); const test2 = new App.yo({name: 'Cameron'}); test2.sayHello(); test2.sayGoodbye();定义constructor,因为它没有做任何事情。 JavaScript引擎将为我们创建一个,如下所示:

yo