有没有一种方法可以将原型添加到变量(数字)中,并且原型可以更改变量本身?

时间:2019-07-02 09:44:18

标签: javascript prototype

我知道向原始javascript对象添加原型是一个坏主意,但是我想向诸如Number.limit(min, max);之类的变量添加原型,在该变量中原型可以更改该变量。

Number.prototype.limit = function(min, max) {
    if (this < min) {
        this =  min;
    } else if (this > max) {
        this = max;
    }
};

使用this似乎会导致分配错误的左侧无效

我已经搜索过Google,并且堆栈溢出,但是没有任何问题可以回答我的问题

那有可能吗?以及我该怎么做?

1 个答案:

答案 0 :(得分:1)

不,在大多数情况下是不可能的-最好的办法是返回新值,呼叫者会重新分配该新值:

Number.prototype.limit = function(min, max) {
  if (this < min) {
    return min;
  } else if (this > max) {
    return max;
  }
  return this;
};
let num = 5;
let newNum = num.limit(10, 15);

console.log(newNum);

如果您熟悉Javascript,要了解为什么为什么,可能会有助于在没有实现的情况下查看方法的调用:

let someVar = <something>;
someMethod(someVar);

无论someMethod做什么,someVar都不能更改someMethod绑定到的对象或图元(除非someMethodsomeMethod也定义在该范围内,这是一个怪异的现象,通常不是这种情况)。除非someVar的词法范围也为someVar = <somethingElse>并且没有someVar,否则<something>将继续引用someMethod。尽管<something>可以对someVar进行变异,但是如果它是一个对象,则不能在其他范围内重新分配 let k = "active EQ 'true' " let i = k.replacingOccurrences(of: "'", with: "") let j = i.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) print("j is \(j!)") 变量名。