JavaScript函数调用

JavaScript函数调用,javascript,function,object,Javascript,Function,Object,我在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(a

我在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
vs
testObj
),但是在更正了这一点之后,下面是发生的情况:

功能测试(){
this.testParam1=“添加”;
this.tstMethod=函数(){
console.log(“你好”);
};
}
var testObj=新测试();
log(testObj.tstMethod());

log(testObj.tstMethod)您的:
console.log(assignTest.tstMethod())是否正常
return
未定义
,因为您的函数不返回某些内容,它只是打印一些内容

如果需要:
console.log(assignTest.tstMethod())
要返回某些内容,您应该在
tstMethod
函数
中执行返回“Hello”这会起作用

另外,未定义
assignTest
,应将其重命名为:
testObj

下面是我用来测试它的代码:

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

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

希望我能帮助你

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

但您确实将其作为函数调用了……这到底是什么?
assignTest
?抱歉,在从本地复制粘贴时,我没有将assignTest更新到testObj。嘿,Robby,感谢您的解释,在从本地复制粘贴时,我没有更新“testObj”。但是当调用该方法时,我希望控制台中出现“Hello”!!我可以知道,为什么没有发生?