本文實例總結了JavaScript中this關鍵字用法。分享給大家供大家參考,具體如下:
例1:
function a(){  var user = "yao";  console.log(this.user);//undefined  console.log(this);//window}a();等價于:
function a(){  var user = "yao";  console.log(this.user);//undefined  console.log(this);//window}window.a();this指向的是window。
例2:
var o = {  user:"yao",  fn:function () {    console.log(this.user);//yao  }}o.fn();this指向的是o。
例3:
var o = {  user:"yao",  fn:function () {    console.log(this.user);//yao  }}window.o.fn();this指向的是o。
var o = {  a:10,  b:{    a:12,    fn:function () {      console.log(this.a);//12    }  }}o.b.fn();this指向的是b。
例4:
var o = {  a:10,  b:{    a:12,    fn:function () {      console.log(this.a);//undefined      console.log(this);//window    }  }};var j = o.b.fn;j();綜上所述:
this的指向永遠是最終調用它的對象。
當this遇上函數的return:
例5:
function fn(){  this.user = "yao";  return {};}var a = new fn;console.log(a.user);//undefined例6:
function fn(){  this.user = "yao";  return function(){};}var a = new fn;console.log(a.user);//undefined例7:
function fn(){  this.user = "yao";  return 1;}var a = new fn;console.log(a.user);//yao例8:
function fn(){  this.user = "yao";  return undefined;}var a = new fn;console.log(a.user);//yaothis指向的是函數返回的那個對象。
function fn(){  this.user = "yao";  return null;}var a = new fn;console.log(a.user);//yao雖然:null是對象,但是此時this指向的仍然是函數的實例。
PS:
在"use strict"模式下,this默認的指向是undefined,而不是window。
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答