调用函数ON一个字符串(Javascript)

时间:2015-05-19 01:21:56

标签: javascript function

如何直接在字符串上调用函数?

var test = function(x){
  console.log(x);
};

test();

** 以上日志' undefined'应该如此。

如果我尝试:

"test".test();

我明白了:

"error"
"TypeError: \"test\".test is not a function.

但是测试是一种功能。所以,即使我尝试:

var example = "test";

example.test();

我明白了:

"error"
"TypeError: example.test is not a function

非常感谢任何帮助。

5 个答案:

答案 0 :(得分:3)

为了扩展其他答案,您已经创建了一个名为test()的函数,但该函数不属于任何对象,并且它不属于任何字符串。你还没有为字符串定义一个名为test()的函数,因此错误。

为此,您可以尝试以下方法:

String.prototype.test = function() {
    console.log(this);
};
"hello".test();

在原型上阅读here。本质上,javascript中的对象具有属性和方法,并且它们还具有其原型的属性和方法。

答案 1 :(得分:1)

是的,test是一个函数,但String.prototype.test不是函数。值为undefined并使用调用运算符调用undefined值会引发TypeError

答案 2 :(得分:1)

问题有点不清楚,但如果你试图将一个String作为你的参数传递给函数,那就是

 test("hello");

 var example = "hello";
 test(example);

答案 3 :(得分:0)

您必须首先使用Prototypes

在字符串上定义函数test()

例如:

String.prototype.cleanSpaces = function() {
     return this.replace(" ", '');
};

现在您可以致电"test ".cleanSpaces()

答案 4 :(得分:0)

使用prototype

 String.prototype.test = function () {
    console.log(this.toString());
}

'test'.test();

它将在控制台中输出test