javascript
JavaScript this指向相关内容
1,默認綁定this指向windw對象
?
看代碼:
function test(C){
var a = 123
function b(){};
}
在預編譯環節當中。
OA{
arguments:[1],
this : window,
C : 1,
A : undefined,
b : funtion(){}
}
test(1)
PS: 也就是說,在正常情況下,函數執行,this指向window;
那么有我們想改變this指向,我們該如何做到呢? 看下面
?
2,隱式改變:誰調用this指向誰;
?
看代碼:
var str = '2222';
var obj = {
str:'1111',
b:function(){
console.log(this.str)
}
}
第一步:
obj.b() 會出現什么? // 11111
實現誰調用指向誰
并且我們的dome的onclick事件都是
升級: var fun = obj.b;//fun 存放了 obj.b整個函數的引用
fun() //2222
為什么?誰調用只想誰!
再看一道題:
?
var str = '2222';
var obj = {
str:'1111',
b:function(){
console.log(this.str)
}
}
?
var obj2 = {
str:'33333',
b : function(fn){
fn()
}
}
?
obj2.b( obj.b)// 出現什么?2222
obj2.b = obj1.b
obj2.b();//3333
講解:
obj2.b( obj.b) 相當于obj.b作為實參傳到函數里,形參接收之后,便有了obj.b的函數體引用,那么再
obj2.b里執行的過程中,fn()并沒有對象調用它,只是一個單獨函數體執行,內部走預編譯的過程中。
從中擴展出 setTimeout(function(){ },1000)或者回掉函數也是這個原理
?
?
3,顯式綁定:call apply bind
代碼如下
var str = 'window';
var obj = {
str :'str',
print:function(){
console.log(this.str);
}
}
?
let newPrint = obj.print.bind(window);//bind 返回一個新的this指向的函數
// newPrint();
newPrint.call(obj);//bind只能綁定一次 bind過的函數 this無法在改變
// newnewPrint();
講解,我們想主動改變this的指向,需要的方法call apply bind 。call和apply可以讓函數執行,而bind可以返回一個新的函數體。bind改變this最厲害,bind之后的函數,call和apply都無法改變;
但是有一個方法可以改變this ,那就是下面的new操作符,請看下面
?
4 ,new 操作符
function test(C){
// var this = object.create(test.prototyoe)
// {
// __proto__:test.prototype
//}
var a = 123
function b(){};
}
new test
講解:當new的過程中,函數內部出現// var this = object.create(test.prototyoe);使this發生改變。
?
總結: 四種this綁定的權重(看誰最厲害)
//1,默認綁定(空函數執行,函數單純執行,this指向window) 默認權重
//2,隱式幫定(誰調用this指向誰) 第三權重
//3,顯式綁定 (call apply bind) 第二高權重
//4,new 綁定this 權重是最高的
?
?
二 升級知識:ES6箭頭函數中的this如何邦定?
?
//學習箭頭函數,同學必須知道的幾件事。 重要!!!!
//1,箭頭函數沒有this 沒有arguments surper(class);
//2,箭頭函數不能new ,不當成構造函數來 沒有prototye;
//3,可以表示數據流向 方便JavaScript引擎優化掃碼;
?
看代碼:
var reg = 'window';
var obj1 = {
reg:"reg",
print:() => console.log(this.reg)
}
?
var obj2 = {
reg:"reg",
print:function(){
console.log(this.reg)
}
}
obj1.print() //window
obj2.print() //reg
講解:箭頭函數具有綁定this的能力 ,一旦箭頭函數定義,this已經綁定,并且無法修改;
箭頭綁定規則:綁定里最近的非箭頭函數作用域中的this : 1 找到最近的非箭頭的作用域 2 找this
?
最后再看一個例子:
?
var obj2 = {
reg:'obj',
getName:function(){
let show = () =>console.log(this.reg)
show();
}
}
obj2.getName() //obj
//scope2(show)----->scope1(getName) 'obj'
講解:箭頭函數show執行,找上一個非箭頭函數作用域,發現是getName方法的作用域,然后找this,指向的是obj2,所以最后打印的是 ‘obj’;
轉載于:https://www.cnblogs.com/pandawind/p/9791029.html
總結
以上是生活随笔為你收集整理的JavaScript this指向相关内容的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#操作NPOI插件的HSSFWorkB
- 下一篇: SpringMVC访问静态资源的三种方式