简体   繁体   English

我可以分配对象运算符吗? “例如+,-”

[英]Can I assign Objects operators? “e.g. +, -”

So I have a simple Javascript Object: 所以我有一个简单的Javascript对象:

function Vector(x, y){
     this.x = x;
     this.y = y;

     this.magnitude = function(){};
     this.add = function(vector){};
     this.minus = function(vector){};
     this.normalise = function(){};
     this.dot = function(vector){}  

     //...
}

I would like to perform the following operations: 我要执行以下操作:

var a = new Vector(1,1);
var b = new Vector(10,5);
var c = a + b
a += c;
// ... and so on

I know that it's possible to implement operators for Objects in other languages, would be great if I could do it in Javascript 我知道可以用其他语言实现对象的运算符 ,如果我可以用Javascript来实现,那将是很好的


Help would be very much appreciated. 帮助将不胜感激。 Thanks! 谢谢! :) :)

This isn't possible in JavaScript. 这在JavaScript中是不可能的。

You can specify what happens to your object in numerical contexts: 您可以指定在数字上下文中对象发生的情况:

Vector.prototype.valueOf = function() { return 123; };

(new Vector(1,1)) + 1; // 124

... but I don't think this is what you're after. ...但是我不认为这就是你所追求的。

How about offering a plus method? 如何提供plus方法? - -

Vector.prototype.plus = function(v) {
    return /* New vector, adding this + v */;
};

var a = new Vector(1,1);
var b = new Vector(10,5);
var c = a.plus(b);

Sorry, ECMAScript/Javascript doesn't support operator overloading. 抱歉,ECMAScript / Javascript不支持运算符重载。 It was proposed for ECMAScript 4 but the proposal wasn't accepted. 它是为ECMAScript 4提出的,但是没有被接受。 You can still define a method which does the same thing as + , though -- just call .add() instead. 不过,您仍然可以定义一个与+具有相同功能的方法-只需调用.add()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript函数就像对象,即“$”可以用作函数,例如$()以及对象$ - Javascript Function like Objects i.e. “$” can be used as a function e.g. $() as well as an object $ 是否可以为游戏对象分配函数钩子,例如在init,death等上运行函数? - Is it possible to assign function hooks to game objects, e.g. run function on init, death, etc? 全局对象(例如Array)是Javascript编程语言的一部分吗? - Is global objects (e.g. Array) are part of Javascript programming Language? 从数组中获取对象数组(例如,字符串) - Get array of objects from array (of strings e.g.) 如何生成特定颜色的随机阴影列表? (例如橙色的随机阴影) - How can I generate a list of random shades of a particular color? (e.g. random shade of orange) 我可以对JavaScript设置时间限制(例如,使用iframe)吗? - Can I put impose a time limit on JavaScript (e.g., using an iframe)? 如何在PHP中使用Ajax从网站(例如IMDB)中获取数据 - How can I fetch data from a website (e.g. IMDB ) using Ajax in PHP 如何使用 kotlin JS 测试 UI? (例如在页面上有一个元素) - How can I test UI with kotlin JS? (e.g. have an element on a page) 在内部链接上,例如到#id,是否触发了一个事件,可以将处理程序附加到该事件? - On an internal link, e.g. to #id is there an event fired that I can attach a handler to? 当用户输入特殊字符时如何显示菜单或下拉列表,例如 % - How can I have display a menu or dropdown list when user enters a special character e.g. %
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM