this.高能

来源:互联网 发布:2017网络黄金egd骗局 编辑:程序博客网 时间:2024/06/10 09:49

1.全局里的this===window

this.document==window.document

2.一般函数里的this==window,严格模式下this==undefined,由对象调用时this指向该对象

function f1(){return this;//this==window}function f2(){"use strict";//严格模式return this;//undefined}var test={};test.f1()// return test对象

3.arguments对象

在函数内部默认有一个类数组对象arguments,可以通过数组形式arguments[index]读写形参,

但在严格模式下arguments对象不能修改形参。arguments对象不具备一般数组的方法

test(10);test.length;//2 返回test方法的形参个数test.name;//“test”返回test方法的名字function test(a,b){console.log(arguments.length); //1 返回调用方法的实参个数console.log(arguments[0]);// 10console.log(arguments[1]);// undefined  没有传的形参,则为undefiend,并且无法通过arguments对象修改arguments[0]=100;console.log(arguments[0]);//100  第一个参数已被arguments对象修改console.log(arguments[1]);// undefined  没有传参将无法被arguments修改 始终未undefiend}

如果函数内有“use strict”--严格模式,那么arguments对象将不能修改任何参数,只能读取

4.call方法,bind方法,apply方法,作用相同,指定调用函数的this对象,只是传参方式不同

function test(a,b){return this.a+a+b;}test.call({a:10},5,10);//25   call函数为test函数指定this所指对象   test=={a:10}var f1=test.bind({a:10});f1(5,10);//25   call函数为test函数指定this所指对象   test=={a:10}var f2=test.bind({a:10},5,10);f2();//25   call函数为test函数指定this所指对象   test=={a:10}test.apply({a:10},[5,10]);// 25  apply函数为test函数指定this对象  test=={a:10},apply以数组方式传参

test.call/apply/bind(null/undefined);此时函数的this对象指向window,在严格模式下,则分别指向null和undefined

5.bind方法也可颗粒化函数

function test(a,b,c){return a+b+c;}var f1=test.bind(undefined,100);f1(1,2);//103   bind方法颗粒化test函数的参数 a绑定为100  b=1 c=2var f2=f1.bind(undefined,200);f2(1);//301  f1的参数a已绑定为100  方法f2又将参数b颗粒化为200  那么c=1

6.当含有this的函数被new 调用时,this则指向新构造出的对象{}

function  test(){this.b=10;return this;}new test();//此时this指向新对象{},在函数test()执行完后,此对象被赋值为{b:100}

原创粉丝点击