javascript中的self和this之间的区别以及何时使用它们中的任何一个 [英] Difference between self and this in javascript and when to use either of them
问题描述
我很困惑,何时在javascript中使用self和this。
我知道 this 指的是当前上下文和 self 指当前窗口。
我正在使用Titanium开发应用程序。我想知道何时使用 self 或 this
或者在钛开发中是否存在 self 的概念。
I am confused that when to use self and this in javascript.
I know that this refers to current context and self refers to current window.
As I am developing an application in Titanium. I want to know when to use self or this
OR does is there is any concept of self in titanium development.
这里是我在我的钛commonJS模块中做的示例代码
here is the sample code that i am doing in my titanium commonJS module
var auth = require('/SDKTest/auth');
var nodeAPI = require('/SDKTest/nodeAPI');
function myAPI() {
this.auth = auth;
this.nodeAPI = nodeAPI;
return this;
}
module.exports = myAPI;
此代码有效,但我可以使用 self 代替这个?
而不是使用 this 我可以创建一个命名空间并执行以下操作:
This code works, but can I use self in place of this ? And instead of using this i can create a namespace and do something like this:
function myAPI() {
var api = {};
api.auth = auth;
api.nodeAPI = nodeAPI;
return api;
}
这两种方法都有效,但使用这是什么用途在这里
both the approaches work but what is the use of using this over here
推荐答案
你的问题有些令人困惑,就像问:我买苹果还是西红柿?答案是,这实际上取决于你想做什么,因为它们完全不同。
Your question is somewhat confusing, it's like asking: Do I buy apples or tomatoes? The answer is, it really depends on what you want to do, since they're completely different.
基本上,你已经在一定程度上回答了你自己的问题,因为你已经知道两者之间的差异:
Essentially, you have answered your own question to some extent, because you already know the differences between the two:
-
这个
是指当前的上下文 -
self
指窗口
this
refers to the current contextself
refers towindow
function myAPI() {
this.auth = auth;
this.nodeAPI = nodeAPI;
return this;
}
module.exports = myAPI;
你问是否可以使用 self
相反。想想看,这个
允许你做什么?它允许您参考上下文。什么是上下文,当你调用 module.exports()
时,它是模块
。并且模块
很可能不会是窗口
,所以不,你不能使用自我
这里。
You're asking whether you can use self
instead. Think about it, what does this
allow you to do? It allows you, to refer to the context. What is the context, well, it's module
when you call module.exports()
. And module
is most likely not going to be window
, so no, you can't use self
here.
那回答了这个问题吗?
第二个代码例子似乎做了一些完全不同的事情。我不知道该怎么做。
The second code example seems to do something completely different. I don't know what to make of that.
这篇关于javascript中的self和this之间的区别以及何时使用它们中的任何一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!