我正在使用原型的独立类继承: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 undefined
类yo
的错误。
如何正确地继承我的hello
课程?
答案 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;
请注意,我们根本不需要为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