我有bar
一个function(foo
)的instance(),但是bar.constructor.name
返回"Object"
而不是"foo"
。谁能告诉我我做错了什么?
代码:
function foo(text){
this.text = text;
}
foo.prototype = {
getUppercase: function(){
return this.text.toUpperCase();
}
}
var bar = new foo("bar");
console.log(bar.constructor.name); //logs "Object" in Chrome
当您将对象替换为函数的prototype
属性时,您必须负责constructor
在其上修复该属性:
foo.prototype = {
constructor: foo, // <====
getUppercase: function() {
return this.text.toUpperCase();
}
};
这不是自动的。prototype
最初创建函数时,该属性的唯一自动填充位于分配给函数属性的默认对象上。
function foo(text){
this.text = text;
}
foo.prototype = {
constructor: foo,
getUppercase: function() {
return this.text.toUpperCase();
}
};
var bar = new foo("bar");
console.log(bar.constructor.name);
或者,不要替换上的默认对象prototype
,只需增加它即可(通常是我的偏好):
foo.prototype.getUppercase = function() {
return this.text.toUpperCase();
};
您可以通过Object.defineProperties
或Object.assign
(后者可能需要垫片)或自己的实用程序功能执行多个操作。
最后,如果我不注意以下几点,我会很失落:
绝大多数情况下,构造函数名称在JavaScript中以大写字母开头。这是只是一个约定,但它是一个非常,非常完善的惯例。
在ES2015 +中,您可以使用class
更简洁的版本:
Function#name
是ES2015的新功能,在我于2016年7月撰写本文时,支持有点粗略。(Chrome 51+确实有此功能。)
FWIW:
class Foo {
constructor(text) {
this.text = text;
}
getUppercase(){
return this.text.toUpperCase();
}
}
var bar = new Foo("bar");
console.log(bar.constructor.name);
当然,如果您需要支持较旧的引擎(例如IE11),则需要进行翻译...(但是再次,如果您使用Function#name
,那也来自ES2015。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句