![](/img/trans.png)
[英]Using JQuery to bind “focus” and “blur” functions for “window”, doesn't work in IE
[英].bind() doesn't work for functions
我正在嘗試使用放置在函數內的變量。 我不想對這段代碼做任何特別的事情,但是我想弄清楚為什么綁定/應用/調用對對象而不是函數起作用。
function another () {
this.var = 'another test'
}
function test (){
this.var = 'test123'
console.log('this.first: ',this.var);
}
var bind = test.bind(another);
console.log('bind: ', bind());
.bind()
對於函數正常工作。 它只是沒有按照您的想法去做。
看,函數也是對象。 像對待對象一樣對待它們並不意味着它們會被調用。
function a() { console.log("a was called"); }
function b() { console.log(this); }
var bound = b.bind(a);
bound(); // logs "function a() { }" in my console
在你的情況,一旦你勢必test
到another
,你有作品就像一個新的功能test
,但如果this
意味着another
,從而this.var
意味着another.var
。 所有這一切都發生了,而沒有another
被稱為 。
我不確定您希望代碼如何工作,因為它看起來並不合理。 但是,如果要在運行它之后檢查事物,您會發現another.var
現在具有值'test123'
。
即使您事先說過another()
也沒關系。 首先,因為another
不受任何約束,所以對它來說, this
意味着全局對象。 在瀏覽器中, another()
基本上只是設置window.var
。 但是其次, test
設置了自己的值-因此,即使兩個函數對this.var
含義有相同的了解, test
也會用'test123'
覆蓋它。
這將記錄“另一個測試”,因為this
默認為window
:
function another() {
this.foo = 'another test';
}
another();
console.log(window.foo);
編輯:
// define function object window.first:
function first() {
this.foo = 'first';
}
// define function object window.second:
function second() {
this.foo = 'second';
}
// call window.first, sets window.foo to 'first':
first();
// set window.bound to a new function object which
// runs second in the context of the object first:
var bound = second.bind(first);
// call window.bound, which sets window.first.foo to 'second':
bound();
// call second, which sets window.foo to 'second' then logs the return
// value of second, which is undefined:
console.log('second: ', second());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.