【问题标题】:JavaScript function invokeJavaScript 函数调用
【发布时间】:2017-08-08 01:24:05
【问题描述】:

我在 JS 中创建了如下对象:

function test(){

  this.testParam1 = "add";

  this.tstMethod = function(){

  console.log("Hello")  ;   

 };

}

var testObj = new test();

console.log(assignTest.tstMethod());  ---> it prints value as undefined
console.log(assignTest.tstMethod);  ----> it prints the function

谁能解释一下为什么我们不能调用tstMethod作为函数?

【问题讨论】:

  • 但是你确实将它作为一个函数调用...
  • assignTest 到底是什么?
  • 抱歉,我在从本地复制粘贴时错过了将 assignTest 更新为 testObj。

标签: javascript function object


【解决方案1】:

您的对象名称不匹配(assignTesttestObj),但在更正之后,这是发生了什么:

function test() {
  this.testParam1 = "add";

  this.tstMethod = function() {
    console.log("Hello");
  };
}

var testObj = new test();

console.log(testObj.tstMethod());
console.log(testObj.tstMethod);

这将给出以下输出;请注意tstMethod 被正确调用:

Hello                         // printed by tstMethod upon its invocation
undefined                     // the return value of tstMethod
this.tstMethod = function() { //
  console.log("Hello");       // the tstMethod function itself
};                            //

【讨论】:

  • 嘿,罗比,感谢您的解释,我错过了在从本地复制粘贴时更新“testObj”。但是当调用该方法时,我期待控制台中出现“Hello”!我可以知道,为什么没有发生这种情况?
【解决方案2】:

您的:console.log(assignTest.tstMethod()); 返回 undefined 是否正常,因为您的函数没有返回某些内容,它只是打印一些内容。

如果你想让这个:console.log(assignTest.tstMethod()); 返回一些东西,你应该在你的 tstMethodfunction return "Hello"; 里面做这件事。

还有assignTest没有定义,你应该重命名为:testObj

这是我为测试它而编写的代码:

function test(){
    this.testParam1 = "add";
    this.tstMethod = function(){
        return "Hello";
    };
}

var testObj = new test();
console.log(testObj.tstMethod());

希望能帮到你!

【讨论】:

    【解决方案3】:

    () 运算符是导致函数被调用的原因。当您访问没有() 运算符的函数时,将返回函数定义。这就是您上次调用 console.log 时发生的事情。

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2012-09-28
      • 2011-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      相关资源
      最近更新 更多