在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ 關(guān)于Js對(duì)象內(nèi)部的函數(shù)調(diào)用

關(guān)于Js對(duì)象內(nèi)部的函數(shù)調(diào)用

代碼大體框架如下:

var page ={
    init:function () {
        this.onLoad();
        setTimeout('this.bindEvent()',2000);
    },
    onLoad:function () {
        ...
    },
    bindEvent:function () {
        ...
    },
    ...
}

為什么老是提示:

mark

回答
編輯回答
局外人
// 全局變量 page
var page = {
init:function () {
    this.onLoad();
    // 定時(shí)器 執(zhí)行函數(shù) 還是別傳字符串的好 很容易進(jìn)坑
    setTimeout('this.page.bindEvent()',2000);
},
onLoad:function () {
    alert('A');
},
bindEvent:function () {
    alert('B');
}

}

page.init();

2018年1月21日 23:38
編輯回答
掛念你

setTimeout('this.bindEvent()',2000);
這里 this 指向 window 吧,
看錯(cuò)了,抱歉。

2018年2月11日 21:53
編輯回答
嫑吢丕

setTimeout()使用字符串作為第一個(gè)參數(shù)時(shí),js內(nèi)部將會(huì)調(diào)用eval()函數(shù)來動(dòng)態(tài)執(zhí)行,而eval()函數(shù)動(dòng)態(tài)執(zhí)行腳本時(shí),并沒有在全局作用域找到bindEvent()這個(gè)函數(shù)。

setTimeout('console.log(this)',2000);//window

eval()函數(shù)有太多不可預(yù)知的危險(xiǎn),所以一般不推薦使用字符串作為setTimeout()的第一個(gè)參數(shù)

setTimeout(this.bindEvent,2000);這樣就可以啦

2017年9月9日 23:16
編輯回答
怪痞
var page ={
    init:function () {
        this.onLoad();
        setTimeout(this.bindEvent,2000);
    },
    onLoad:function () {
        console.log('A');
    },
    bindEvent:function () {
        console.log('B');
    }
}
page.init()

換種不給bindEvent綁全局作用域的寫法:

var page ={
    init:function () {
        this.onLoad();
        setTimeout(function(){
            page.bindEvent();
        },2000);
    },
    onLoad:function () {
        console.log('A');
    },
    bindEvent:function () {
        console.log('B');
        this.omg();
    },
    omg:function () {
        console.log('C')
    }
}
page.init();
2017年5月9日 18:14
編輯回答
乖乖瀦
 init:function () {
        this.onLoad();
        setTimeout('this.bindEvent',2000);
    },

改成上面這樣,this.bindEvent是一個(gè)函數(shù),this.bindEvent()是執(zhí)行這個(gè)函數(shù),得到的結(jié)果是一個(gè)該函數(shù)的返回值,而setTimeout期望這個(gè)位置是一個(gè)函數(shù)而不是一個(gè)值

2017年6月24日 02:09