javascript之this

來源:互聯網
上載者:User

標籤:add   style   bin   this   建立對象   作用   bsp   object   fine   

全域範圍的this

 

this == window   //truethis.a  = 8 window.a  //8

 

一般函數的this

 

 

function thisTest(){   return this;}thisTest() === window   //truefunction thisTest(){   ‘use strict‘   return this;}thisTest() === undefined   //true

 

作為對象方法的函數中的this

 

var o  = {  x:1,  y:2,  f:function(){       return this.x}}o.f()  //x    做為對象方法函數中this,指向的是這個對象 

 

對象原型鏈的上this

 

var o  = {f:function(){retrn this.a+this.b}}var obj = Object.create(o)obj.a = 90;obj.b = 10;obj.f()  //100   原型鏈上的this,指向obj

 

構造器中的this

 

function fuc(){   this.a = 37;}var f = new fuc();f.a   //37   

function func(){ this.a = 65; return 1;}var func = new func();func.a //65

function  funct(){   this.a = 65;   return {x:1};}var funct = new funct();funct.x  //1

// 通過new構造器建立對象時
// 1 沒有return 或者 return時基本類型的時候。返回this. (this的原型指向this所在的函數)
// 2 返回的是物件類型,會將return的對象作為傳回值

 

call/apply方法與this

 

function add(c){  return this.a+this.b+c}var o = {a:2,b:4}add.call(o,4)  //10  call第一個參數傳入要作為this的對象,後面參數傳入函數參數列表中的參數,並以逗號隔開

function add1(c){  return this.a+this.b+c}var o1 = {a:2,b:4}add1.apply(o,[4])  //10    apply第一個參數傳入要作為this的對象,後面參數傳入函數參數列表中的參數,作為數組傳入

 

function fuc(x,y){
console.info(x,y,this)
}

fuc.call(1,7,6);  //7 6 Number

 

fuc.call(null); //undefined undefined Window

 

fuc.apply(null); //undefined undefined Window  

 

fuc.call(undefined); //undefined undefined Window

 

fuc.apply(undefined); //undefined undefined Window  在一般模式下,call,apply傳入null,undefined指向的window

 

bind方法與this

 

function z (){   return this.a};var g = z.bind({a:"89"});g()   //"89"var o = {a:4,f:z,g:g};o.f()  //4   函數作為對象方法,this指向o對象,所有 o.f()為4o.g() // "89"  bind方法綁定了z()中this的指向為{a:"89"}

 

javascript之this

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.