我可以用 +/- 等扩展对象吗?

发布于 2024-10-31 09:47:27 字数 441 浏览 1 评论 0原文

我尝试使用运算符扩展本机对象。有用。你能想到会有副作用吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦年海沫深 2024-11-07 09:47:27

您所做的事情不应该有任何副作用。请记住,您不要将您正在做的事情称为“运算符重载”,否则代码的用户可能会认为他们实际上可以使用运算符。您可能还想问自己,“这真的会让编写代码变得更容易吗?”

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?"

牛↙奶布丁 2024-11-07 09:47:27

我看不出这会产生什么影响。看起来唯一的方法是通过拼写错误,之前通知开发人员没有这样的运算符(我假设),但现在它会让你这样做。虽然我不是一个经验丰富的 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.

风轻花落早 2024-11-07 09:47:27
alert( 'hello '['+']('world ','and ','see you later!') );

是的,这样做有一个副作用 - 它使你的代码不可读。当你想出这个计划的时候你到底在抽什么烟?

另外,你所做的与运营商无关。您只是创建一个名称恰好为“+”或“+++”的对象属性。如果解释器认为“+”字符是运算符,则它只是一个运算符。如果它位于字符串文字内,那么它只是另一个字符。

alert( 'hello '['+']('world ','and ','see you later!') );

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文