javascript之this

全局作用域的this


 

this == window   //true

this.a  = 8 

window.a  //8

 

一般函数的this


 

 

function thisTest(){
   return this;
}


thisTest() === window   //true


function 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()为4

o.g() // "89"  bind方法绑定了z()中this的指向为{a:"89"}

 

posted @ 2017-06-24 23:10  心碎whn  阅读(158)  评论(0编辑  收藏  举报