2017-02-14 34 views
0

我使用原型的独立的类继承: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

只是把它那里:PrototypeJS的'Class'东西是过时,PrototypeJS是不是真的保持多少这些天。您最好学习ES2015中引入的新“类”语法(又名“ES6”),并根据需要为旧版浏览器进行转译。 –

回答

1

的问题是,yoinitializer不传递参数,你把它传递给超:

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

因此,在hello代码的initialize函数试图从阅读name财产args,但是argsundefined。因此错误。

更新工作示例:

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();
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.3/prototype.min.js"></script>


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

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();

请注意,我们根本不需要为yo定义constructor,因为它什么都不做。 JavaScript引擎将创造一个对我们来说,这看起来是这样的:

constructor(...allArguments) { 
    super(...allArguments); 
} 
+0

波什!这很好,谢谢。 – Cameron

+0

新的ES6东西看起来不错...但它不支持IE吗? – Cameron

+0

@Cameron:不,但您可以使用[Babel](http://babeljs.io)等工具作为分发构建过程的一部分进行传输。 –