gpt4 book ai didi

javascript - phonegap javascript 模板解释寻求使用 this 关键字

转载 作者:行者123 更新时间:2023-11-30 17:50:47 25 4
gpt4 key购买 nike

我不知道该怎样称呼这个问题,因为它有点大。

我从基本模板 Phonegap 下载了代码。

有一个代码示例:

var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');

listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');

console.log('Received Event: ' + id);
}
};

为什么是“app.receivedEvent('deviceready');”而不是“this.receivedEvent('deviceready');”

我试图理解,但我就是无法理解。

谁能给我解释一下?

谢谢:)

最佳答案

评论解释了原因。

您需要通知应用程序设备已准备就绪。上下文中的 this 对象就是事件本身。

这就像调用 event.receivedEvent

您需要通知应用程序设备已准备就绪,因此调用 app

编辑:为了进一步说明,thisapp 的上下文,除了 onDeviceReady 函数中的 app 对象。 bindEvents 函数运行这段代码:

document.addEventListener('deviceready', this.onDeviceReady, false);

它通过 addEventListeneronDeviceReady 绑定(bind)到一个事件,该事件将 this 的上下文从 app 更改为 事件

这意味着,您不能通过具有已更改上下文的 this 关键字从 app 调用方法。希望这有助于进一步澄清。

编辑 2:请参阅此代码进行一些演示:http://jsbin.com/UGerika/1/edit?html,js,output

    // http://jsbin.com/UGerika/1/edit?html,js,output
// Demonstrates the scope of 'this' variable once a
// function is bound to event receiver.

var app = {
var1: function(){
return "i am this";
},

initialize: function() {
this.bindEvents();
},

bindEvents: function() {
alert('bindevents');
this.onWindowClick();
},

onWindowClick: function() {
// in this case, this.var1 is perfection valid
// 'this' is still scoped to 'app' object.
alert(this.var1);
}

};


var app2 = {
var1: function(){
return "i am this";
},

initialize: function() {
this.bindEvents();
},

bindEvents: function() {
alert('bindevents');
document.addEventListener('mousedown', this.onWindowClick, false);
},

onWindowClick: function() {
// in this case, this.var1 is invalid
// 'this' is scoped to 'mousedown' event.
// we would have to call app2.var1
alert(this.var1);
}

};

关于javascript - phonegap javascript 模板解释寻求使用 this 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19099498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com