JavaScript 原型继承:语法简洁?
有没有比三个不同的程序操作更简洁的方式来表达这一点?更像对象表示法的东西,或者至少都在 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"
Is there a more succinct way to express this than three distinct, procedural operations? Something more object notation-like, or at least all within the body of the Name
function?
Problem:
function Name(first, last) {
this.first = first;
this.last = last;
}
Name.prototype = new String;
Name.prototype.toString = function() {
return this.last + ', ' + this.first;
};
Test:
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'
}));
Expected output:
< "dean, jimmy"
< true
< true
< true
< "dean, jimmy"
< "dean, jimmy"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
示例
Example
我是这样做的:
Here's how I do it:
当然。使用
Object.create
。现在ES5有点难看,所以你可以使用ES5 OO Sugar的一些机制,我们以pd为例:
当然输出是符合预期的实例
Sure. Use
Object.create
.Now ES5 is a bit ugly, so you can use some mechanism for ES5 OO sugar, let's take pd as an example:
Of course output is as expected Live Example