【发布时间】:2011-12-21 21:06:28
【问题描述】:
有没有比三个不同的程序操作更简洁的方式来表达这一点?更像对象符号的东西,或者至少都在 Name 函数的主体中?
问题:
function Name(first, last) {
this.first = first;
this.last = last;
}
Name.prototype = new String;
Name.prototype.toString = function() {
return this.last + ', ' + this.first;
};
测试:
console.log(new Name("jimmy", "dean").toString())
console.log(new Name() instanceof Name);
console.log(new Name() instanceof String);
console.log(new Name() instanceof Object);
console.log(Name.prototype.toString.call(new Name('jimmy', 'dean')));
console.log(Name.prototype.toString.call({
first: 'jimmy',
last: 'dean'
}));
预期输出:
< "dean, jimmy"
< true
< true
< true
< "dean, jimmy"
< "dean, jimmy"
【问题讨论】:
-
吹毛求疵;你的意思是
partFirst吗? -
@pimvdb — 有时最好只编辑小错字的问题。
-
我不明白您为什么希望原型成为 String 的实例。只要 toString 返回一个字符串(这似乎是明智的),那么您可以调用任何将从 String 继承的方法,而无需将字符串分配给构造函数的原型。
标签: javascript inheritance prototypal-inheritance