欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Javascript中的this,bind和that使用實(shí)例

 更新時(shí)間:2019年12月05日 10:34:53   作者:Narcissu5  
這篇文章主要介紹了Javascript中的this,bind和that使用實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

這篇文章主要介紹了Javascript中的this,bind和that使用實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

Javascript中必須通過this來(lái)訪問類成員,可是this的特點(diǎn)就是函數(shù)綁在哪個(gè)對(duì)象上,它就指向那個(gè)對(duì)象。這個(gè)可能困擾過很多的程序員,特別是從C#,Java等語(yǔ)言過來(lái)的程序員。

function Foo(){
  this.message = 'This is message from Foo';
}

Foo.prototype.printMessage = function(){
  console.log(this.message);
}

function Foo2(){
  this.message = 'This is message from Foo2';
}

var foo = new Foo();
foo.printMessage();

var foo2 = new Foo2();
foo2.printMessage = foo.printMessage;
foo2.printMessage();

輸出為:

This is message from Foo

This is message from Foo2

主要原因就是this改變了,因此Javascript中this的用法,和C++\C#中的大為不同。如果需要傳統(tǒng)方式使用this的函數(shù),可以使用Function.prototype.bind(),指定函數(shù)的this值:

function Foo(){
  this.message = 'This is message from Foo';
  
  this.printMessage = (function(){
    console.log(this.message);
  }).bind(this);
}

function Foo2(){
  this.message = 'This is message from Foo2';
}

var foo = new Foo();
foo.printMessage();

var foo2 = new Foo2();
foo2.printMessage = foo.printMessage;
foo2.printMessage();

輸出為:

This is message from Foo

This is message from Foo

另外使用call和apply也可以改變函數(shù)調(diào)用時(shí)的this值。

bind函數(shù)的主要問題是IE9以后才開始提供。并且一旦開始習(xí)慣了Javascript的this用法,這種bind反而會(huì)不習(xí)慣。在實(shí)踐中,更多用到的還是保存this:

function Foo(){
  var that = this;
  
  this.message = 'This is message from Foo';
  
  this.printMessage = function(){
    console.log(that.message);
  };
}

function Foo2(){
  this.message = 'This is message from Foo2';
}

var foo = new Foo();
foo.printMessage();

var foo2 = new Foo2();
foo2.printMessage = foo.printMessage;
foo2.printMessage();

輸出同上。

注意我們是通過that來(lái)訪問的message(除了that,context和self也是常用的名稱)。Javascript一個(gè)還算欣慰的地方就是他的閉包上下文始終是在函數(shù)定義的地方,因此不管函數(shù)被掛上哪個(gè)對(duì)象上,捕獲到的that始終是這個(gè)。當(dāng)然這個(gè)地方不算閉包,有閉無(wú)包,但原理是相同的。這也是實(shí)踐中用的最多的方法,推薦使用。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論