【问题标题】:Javascript Function with String/Object attached to it [duplicate]附加了字符串/对象的Javascript函数[重复]
【发布时间】:2018-06-14 12:42:51
【问题描述】:

在javascript中,我想写一个函数,调用如下:

var x = 'testString'
var y = 'anotherstring'
var z = 0

var result = x.aFunction(y, z)

function aFunction(y, z) {
  ...
}

这是我第一次尝试这个,我的问题是如何在函数 aFunction 中获取和使用 x 的值,而不实际参考声明变量。

我试图寻找这个,但我找不到任何东西。如果有任何人知道的专门针对此的帖子,请告诉我。

谢谢

【问题讨论】:

  • 你想让aFunction成为一个字符串方法吗?
  • 为什么你想做……好吧,不管你问的是什么?您要解决的实际问题是什么?
  • 如果在原型中定义了函数aFunction,您可以使用this引用调用函数的外部变量。
  • 我希望它类似于 charAt() 原生 javascript 函数,用作:string.chartAt(0)

标签: javascript function


【解决方案1】:

您需要使用String.prototype.aFunction,以便您可以将自定义函数aFunction() 添加到String 的原型中,以便可以通过字符串变量调用它。此外,原型函数中的this.toString() 将为您提供x 变量的值(调用字符串)

var x = 'testString'
var y = 'anotherstring'
var z = 0

String.prototype.aFunction = function(y, z){
  console.log(this.toString());
  return y+z;
}
var result = x.aFunction(y, z);
console.log(result);

【讨论】:

  • "在函数aFunction中如何获取和使用x的值?"
  • 太好了,谢谢,找到了一个类似的帖子,也有帮助
  • @AndreasKarps 很酷。我已经更新了答案,看看吧
  • @deceze 感谢您的指点
猜你喜欢
  • 2018-08-31
  • 2016-09-06
  • 2020-04-29
  • 2016-07-13
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 2019-03-24
  • 2017-03-10
相关资源
最近更新 更多