我有以下文件:
run.js
var cat = require('./animal/cat').create('Tom');
console.log( cat.petName );
console.log( cat.paws );
cat.voice();
animal.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
这意味着猫继承了动物。
但是当涉及到调用方法时,会发生以下错误:
TypeError:' undefined'不是构造函数(评估' cat.voice()')
全局代码中的run.js:4
我无法理解这是什么问题。任何人都可以解释错误吗?
答案 0 :(得分:2)
voice
函数是cat()
构造函数的方法,而不是cat
对象(由构造函数返回)。在其他语言中,这称为类方法或静态方法。
要为cat
对象创建方法,需要将其添加到原型中:
cat.prototype.voice = function(){
console.log('myouu');
}
但要注意,在你的cat创建函数中,你会覆盖原型。所以这样做:
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 );
}