[英]Why does a function in my object return undefined?
Consider this code: 考虑以下代码:
var MSE = {
Module : {}
};
MSE.Module = (function() {
'use-strict';
var app = {
tabsPre : function() {
var tabsPre = {
init : function() {
},
changeTab : function(arg) {
return arg;
}
};
tabsPre.init();
return tabsPre;
}
};
return app;
})();
console.log( MSE.Module.tabsPre() );
console.log( MSE.Module.tabsPre().changeTab() ); // undefined
console.log( MSE.Module.tabsPre.changeTab() ); // Uncaught TypeError: MSE.Module.tabsPre.changeTab is not a function
I am trying to access changeTab()
in the tabsPre
object, but I don't seem to be able to. 我试图访问
changeTab()
在tabsPre
对象,但我似乎不能够。 The last two console.log
statements aren't giving me what I had hoped for. 最后两个
console.log
语句没有满足我的期望。 How can I do this? 我怎样才能做到这一点?
Here's a JSFiddle: https://jsfiddle.net/xhb16qL6/ 这是一个JSFiddle: https ://jsfiddle.net/xhb16qL6/
In the first console.log
, I can see the function is there: 在第一个
console.log
,我可以看到该功能:
Any help or guidance on what I'm doing wrong would be great. 任何关于我做错事情的帮助或指导都将非常有用。 I'm probably having a dumb day and can't see it.
我可能有一个愚蠢的日子,看不到它。
Thanks, Mikey 谢谢,Mikey
ChangeTab返回传递给它的args,并且由于未传递任何参数而未定义打印,请尝试:
console.log(MSE.Module.tabsPre().changeTab("args")) //"args"
console.log( MSE.Module.tabsPre() );
this logs the tabsPre object you are returning 这记录了您返回的tabsPre对象
console.log( MSE.Module.tabsPre().changeTab() );
this logs the result of MSE.Module.tabsPre().changeTab()
which is undefined
as you didn't pass an argument 这将记录
MSE.Module.tabsPre().changeTab()
的结果,该结果是undefined
因为您没有传递参数
console.log( MSE.Module.tabsPre.changeTab() );
this causes an error as MSE.Module.tabsPre
is a function, and therefore you cannot access properties of it, as they don't exist 这会导致错误,因为
MSE.Module.tabsPre
是一个函数,因此您无法访问它的属性,因为它们不存在
JavaScript dosen't check for the number of arguments. JavaScript不会检查参数的数量。
Suppose I have a method, say add
and defined like this: 假设我有一个方法,比如说
add
和定义如下:
function add(arg1, arg2){
}
I call this method like in 3 different ways, lets assume: 我以3种不同的方式调用此方法,让我们假设:
1) add(1,2) // Works just fine
2) add(1,2,3) // My third argument is ignored.
3) add(1) // 2nd expected parameter is taken to be `undefined`
Your problem is scenario number 3. 您的问题是方案3。
Your changeTab
method expects ONE argument. 您的
changeTab
方法需要一个参数。 If you dont pass any in your call to changeTab
, you see undefined
. 如果您在对
changeTab
的调用中changeTab
传递任何changeTab
,则会看到undefined
。
The changeTab ()
function expects an argument. changeTab ()
函数需要一个参数。 The code then returns the argument passed once it's called. 然后,代码将返回调用后传递的参数。 Since you didn't pass an argument, then
undefined
is returned. 由于您未传递参数,因此返回
undefined
。
Try passing an argument :) 尝试传递一个参数:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.