Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/470.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript构造函数:无法在func内部调用_Javascript_Constructor - Fatal编程技术网

Javascript构造函数:无法在func内部调用

Javascript构造函数:无法在func内部调用,javascript,constructor,Javascript,Constructor,嗨,我定义了这个脚本: var asdf = { settings : { scope : "blah" }, func1 : function () { alert('1'); }, func2 : function () { this.func1();

嗨,我定义了这个脚本:

var asdf = {                
        settings : {            
            scope : "blah"
        },  
        func1 : function () {
                alert('1');
        },
        func2 : function () {
                this.func1();
        }
}
为什么我不能使用
this.func1()
调用成员func?这很奇怪,因为
这个.settings.scope
工作得非常好

正确的语法是什么?tnx

“为什么我不能使用此.func1()调用成员func?”

只要从
asdf
的上下文调用
func2
,就可以

asdf.func2();  // alerts '1'

如果你做了这样的事

var fn = asdf.func2;

fn();
那么它就不起作用了,除非你手动设置上下文

var fn = asdf.func2;

fn.call(asdf); // set the calling context of "func2" to the "asdf" object

我从您的标签中得知
func2
是一个构造函数?原因是当使用
new
调用函数时,
将是正在构造的对象。例如:

function Constructor() {
    console.log(this);
}

Constructor(); // window
new Constructor(); // instance of Constructor printed out
相反,只需将
func1
作为
asdf.func1
访问即可。无论如何,在那种情况下,如果不使用
这个
,会更安全<代码>此可以绑定到任何内容:

function func() {
    alert('What am I? ' + this);
}

func.call('A String! Weird.'); // Alerts What am I? A String! Weird.

好的,但是为什么我在调用func1时需要“asdf”上下文,而不是在这个.settings.scope变量上?@zsitro:你的问题没有显示你是如何使用
这个.settings.scope的,所以我无法回答这个问题。我只是说如果你做了
asdf.func2
,那么
func2
this
的值就是
asdf
对象。你的问题没有任何问题。如果有一个问题需要解决,你需要在问题中证明它。它似乎有效。。。这是您实际的测试代码吗?或者,您是否创建了这个示例,但没有进行测试以查看它是否显示了您遇到的实际问题?但是您是否进行了测试以查看它是否说明了您的问题?我们看不到您是如何调用
func2
,但是如果您正在执行
asdf.func2()
,那么您的代码就可以工作了。好的,我认为问题是这个.func1()是在FB.api('/me',函数(响应){…请求中调用的,所以这不起作用..Tnx for the fiddle:)