发表于: 2017-03-27 01:18:31
1 1075
今天完成的事情:
看了红宝书基础知识
明天计划的事情:
修改产品提出来的BUG
遇到的问题:
原型继承好多没搞懂,继续看红宝书相关方面知识
收获: 整理下this指向问题
1.全局作用域下的this:window
2.一般函数下的this
一般的函数声明或者函数表达式
function f1(){
return this;
}
指向window
严格模式下指向undefine
3.作为对象方法的函数this
字面量形式:
var o={
prop:37,
f:function(){
return this.prop;
}
}把函数作为对象属性的this指向o
var o={prop:37};
function independent(){
return this.prop;
}
o.f=independent;
this会指向对象o
4.对象原型链上的this
var o={f:function(){return this.a+this.b}}
var p=Object.creat(o);
p.a=1;
p.b=4;
console.log(p.f())
原型上的this指向p
5.get、set方法:
6.构造器中的this
function Myclass(){
this.a=37; //正常调用指向全局对象
}
var o=new Myclass(); //当用new把Myclass当做构造器调用的时候,this会指向空的对象,并且这个空的对象的原型指向Myclass.prototype.即this指向了Myclass.prototype的空对象
console.log(o.a) //37
function c2(){
this.a=37;
return {a:38}; //当return返回值返回的是对象,会将return的对象作为返回值。如果return返回时的是基本类型,返回时是对象a:37
}
o=new C2();
console.log(o.a) //38
7.call/apply方法与this
function add(c,d){
return this.a+this.b+c+d;
}
var o={a:1,b:3}
add.call(o,5,7) //1+3+5+7=16
add.apply(o,[10,20]); //1+3+10+20=34 call与apply基本没什么差别,apply参数是数组形式传进去。
8.bind方法与this
bind方法是ES5才有的方法,IE9+才支持
funtion f(){
return this.a;
}
var g=f.bind({a:"test"})
console.log(g()); //test
函数属性arguments
function foo(x,y,z){
arguments.length; //2 实参个数
arguments[0]; //1
}
foo.length; //3 形参个数
foo.name; //"foo" 函数名
arguments是一个类数组对象,它的原型并不是array.prototype.arguments可以像数组一样通过下标访问值。注意例子有三个参数,如果foo(1,2)第三个z没有传进去,arguments[2]=100,这样复制过后z值还是undefine。
注意严格模式下;arguments[0]=10;这种操作不会改变x的值。
apply和call方法:用法基本一致,call是扁平化传入参数,apply传入的第二个参数是个数组,数组里面分别是每一个参数的值。
foo.call(100,1,2) 对于call 第一个是作为this的对象,如果不是对象就会转成对象因此输出是
//1,2,Number(100) 转换为包装类number
foo.apply(true,[3,4]) //3,4 Boolean(true)
注意:foo.apply(null) //undefine,undefine,window
foo.apply(undefine) //undefine undefine window
在严格模式下:foo.apply(null) //this指向null
foo.apply(undefine) //this指向undefine
bind方法:改变函数的指向
this.x=9;
var module={
x:81;
getX:function(){return this.x}
}
module.getX(); //81
var getX=module.getX;
getX(); //9 这个时候this指向变成了window
var boundGetX=getX.bind(module); //bind把this指向了module
boundGet(); //81
bind除了改变函数里面的this指向,还有柯里化的功能
函数柯里化:把一个函数拆成多个单元。 bind currying(局部调用)
function add(a,b,c){
return a+b+c
}
var func1=add.bind(undefine,100); //bind后面第一个是this指向,不需要改变,所以传了undefine 100是指定a的值
func(1,2) //103
var func2=func.bind(undefine,200) //第二次bind方法,由于a的值已经有了,200是b的值
func2(10); //310
实际例子:
function getConfig(colors,size,otherOptions){
console.log(colors,size,otherOptions)
}
比如前面两个属性值都是确定的,只有第三项我们需要修改
var defaultConfig=getConfig.bind(null,"#CC0000","1024x768");
defaultConfig('123'); //#CC0000 1024x768 123
defaultConfig('456') //#CC0000 1024x768 456
参数复杂,可以使用
评论