我可以用 +/- 等扩展对象吗?
我尝试使用运算符扩展本机对象。有用。你能想到会有副作用吗?
Number.prototype['+++'] = function(n){
return this + (2*n);
};
String.prototype['+'] = function(){
return this += [].slice.call(arguments).join('');
}
alert( 10['+++'](10) ); //=> 30
alert( 'hello '['+']('world ','and ','see you later!') );
//=> hello world and see you later!
另请参阅这个jsfiddle
I tried extending native Objects using operators. It works. Would there be side effects you can think of?
Number.prototype['+++'] = function(n){
return this + (2*n);
};
String.prototype['+'] = function(){
return this += [].slice.call(arguments).join('');
}
alert( 10['+++'](10) ); //=> 30
alert( 'hello '['+']('world ','and ','see you later!') );
//=> hello world and see you later!
see also this jsfiddle
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您所做的事情不应该有任何副作用。请记住,您不要将您正在做的事情称为“运算符重载”,否则代码的用户可能会认为他们实际上可以使用运算符。您可能还想问自己,“这真的会让编写代码变得更容易吗?”
There shouldn't be any side effects to what you're doing. Just keep in mind that you don't call what you're doing "operator overloading," or users of your code might think they can actually use the operators. You may also want to ask yourself, "does this really make writing code any easier?"
我看不出这会产生什么影响。看起来唯一的方法是通过拼写错误,之前通知开发人员没有这样的运算符(我假设),但现在它会让你这样做。虽然我不是一个经验丰富的 javascript 开发人员。
I can't see how that would affect anything. Looks like the only way would be by a typo where before it notify the developer that there is no such operator (I'm assuming) but now it will let you do it. Though I'm not an experienced javascript developer.
是的,这样做有一个副作用 - 它使你的代码不可读。当你想出这个计划的时候你到底在抽什么烟?
另外,你所做的与运营商无关。您只是创建一个名称恰好为“+”或“+++”的对象属性。如果解释器认为“+”字符是运算符,则它只是一个运算符。如果它位于字符串文字内,那么它只是另一个字符。
Yes, there's a side effect to doing stuff like this - it makes your code unreadable. What the hell were you smoking when you came up with this scheme?
Also, what you're doing has nothing to do with operators. You're just creating an object property whose name happens to be "+" or "+++". A "+" character is only an operator if the interpreter considers it to be an operator. If it's inside a string literal, then it's just another character.