当myClass
函数返回单个字符串“hii”时,testClass.getDetails()
工作正常:
function myClass(name, age) {
this.name = name;
this.age = age;
return "hii";
}
myClass.prototype.getDetails = function() {
return "mydetails";
}
var testClass = new myClass('aneesh', 27);
alert(testClass.getDetails());
但是当我在 myClass
中返回一个对象时:
function myClass(name, age) {
this.name = name;
this.age = age;
return {};
}
我收到错误:
testClass.getDetails is not a function
为什么会发生这种情况?在 Javascript 中,字符串也是一个对象,对吗?
最佳答案
不,像您返回的字符串文字 ("hii"
) 是原始值,而不是对象。
在 JavaScript 中,我们有以下原语:字符串、数字、 bool 值、未定义和 null。
如果与 new
运算符一起使用的构造函数返回原语,则将返回 this
值。
如果返回一个对象,就像在第二个示例中一样(IMO 并不是真正有用),新创建的对象(构造函数中的 this
)将丢失,并且您会收到错误,因为它不包含名为 getDetails
的属性。
例如:
function Test () {
// don't return anything (equivalent to returning undefined)
}
new Test() instanceof Test; // true
function Test2 () {
return {};
}
new Test2 instanceof Test2; // false
关于JavaScript 类定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3499703/