標籤: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