1. 程式人生 > >js 中bind

js 中bind

堆內存 console 測試 得出 world! 改變 發生 innerhtml cti

function fn(a){
            this.innerHTML = a;
            console.log(this);
        }
        //fn("hello");
        span1.onclick =function(){
            console.log(this);
             fn.bind(div1)("hello world!"); // 這裏我們得到的this 指向span1
        }
        div1.onclick =function(){
            console.log(
this); //這裏我們得到this指向window; fn(); }

OK! 我們在對點擊span1的fn()時,可以看到 此時span1下的函數this發生了改變;而我們在點擊div1中點擊時,可以看到我們的div1下的this指向window。也就是說原函數並沒有改變。在經過我們測試之後我們得出 bind()方法其實 就是讓我們在堆內存中新copy了一份; 而不是僅僅只是在棧內存中copy了一個地址;其中2個函數是相互不影響的。

給自己加油!!!

js 中bind