我有以下文件:
- run.js(运行整个脚本)
- animal.js(猫的父抽象类)
- animal/cat.js(动物的子类,我想在其上调用方法)
运行.js
var cat = require('./animal/cat').create('Tom');
console.log( cat.petName );
console.log( cat.paws );
cat.voice();
动物.js
function animal(){
this.paws = 4;
}
exports.create = function(){
return new animal();
}
动物/cat.js
function cat( name ){
this.petName = name
}
cat.voice = function(){
console.log('myouu');
}
exports.create = function( name ){
cat.prototype = require('../animal').create();
return new cat( name );
}
当我通过控制台记录 cat 类的属性时,一切正常。提示打印:
汤姆
4
这意味着猫仍然继承自动物。
但是当调用该方法时,出现以下错误:
类型错误:“未定义”不是构造函数(评估“cat.voice()”)
全局代码中的 run.js:4
我只是无法理解发生了什么事。有人能解释一下错误吗?
最佳答案
voice
函数是 cat()
构造函数的方法,而不是 cat
对象(由构造函数返回)。在其他语言中,这称为类方法或静态方法。
要为 cat
对象创建方法,您需要将其添加到原型(prototype)中:
cat.prototype.voice = function(){
console.log('myouu');
}
但要注意,在你的 cat 创建函数中,你会覆盖原型(prototype)。所以这样做:
exports.create = function( name ){
cat.prototype = require('../animal').create();
return new cat( name );
}
如果像我上面显示的示例那样定义,将删除语音方法。正确的做法是,在声明附加方法之前需要继承:
cat.prototype = require('../animal').create();
cat.prototype.voice = function(){
console.log('myouu');
}
exports.create = function( name ){
return new cat( name );
}
关于javascript - Phantomjs javascript继承误区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30457426/