我正在调用以下第 3 方 JavaScript 函数:
var Socket = function(url) {
sockets.push(this);
var me = this;
me.readyState = 0;
window.setTimeout(function() {
me.readyState = 1;
me.onopen();
}, 500);
};
通过此:
connection = new Socket(socketURL);
现在我想尝试一劳永逸地理解在函数内引用 this
的含义。和Java中的一样吗?例如我指的是我自己,还是 JavaScript 中我指的是函数所在的命名空间?
最佳答案
this
的引用取决于您调用该函数的方式。
例如:
function globalFn() { return this.val; }
var objectA = { val: 1, localFn: globalFn };
var objectB = { val: 2, localFn: globalFn };
objectA.localFn(); // `this` will be `objectA`, so it returns `1`.
objectB.localFn(); // `this` will be `objectB`, so it returns `2`.
到目前为止,一切都很好。它看起来与 Java 或其他面向对象语言中的相同。但是,这可能看起来很棘手:
var myFn = objectA.localFn;
myFn(); // `this` will be `undefined` in strict mode, causing an error
这表明 this
引用并不绑定(bind)到函数本身,而是绑定(bind)到函数的调用方式。您可以通过使用函数对象的 call
方法来“欺骗”它:
myFn.call(objectA); // `this` will be `objectA`, returns `1`.
globalFn.call(objectB); // `this` will be `objectB`, returns `2`.
objectA.localFn.call(objectB); // `this` will be `objectB`, returns `2`.
您甚至可以对没有将函数定义为属性的对象执行此操作:
var objectC = {val: 3};
myFn.call(objectC); // `this` will be `objectC` and will return `3`.
一开始很难理解它,YouTube 有一个很棒的视频说明了它的工作原理:The Definitive Guide to Object-Oriented JavaScript作者:詹姆斯·肖尔。
关于javascript - 'this'在javascript函数中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26832347/