js的执行模式:
1.一种是正常模式,第二种是严格模式,现在一般都采用正常模式
正常模式:
function f1(){
console.log(this);
}
f1(); // window
window.f1();//window
严格模式:
"use strict";
function f1(){
console.log(this);
}
f1(); //undefined
window.f1(); //window
call()和apply():
1.call和apply都是Function对象的原型对象上定义的方法,它的作用
就是可以通过call和apply来改变this的指向
2.二者作用:执行函数,并改变函数的指向
3.call方法:call(thisArg, arg1,arg2,......)
4.apply方法:apply(thisArg, [item1,item2,item3,......])
5.如果函数传递过来没有形参,那么通过apply和call来调用时,可以一个参数都不给(包括那个thisArg)。
6.如果不给thisArg,就默认this为window,如果thisArg参数为null,正常情况下,this也默认是window
7.call是一个个返回,apply返回的是一个数组
function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype.sayHi=function(a,b){
console.log("你好:" + this.name + "," + this.age + "; a+b=" +(a+b));
}
var per=new Person('黎明',28);
per.sayHi();//你好:黎明,28; a+b=NaN
function Student(name,age){
this.name=name;
this.age=age;
}
var stu=new Student("黑夜",30);
per.sayHi.call(null);//你好:,undefined
per.sayHi.call(stu,3,4);//你好:黑夜,30; a+b=7
per.sayHi.apply(stu,[5,6]);//你好:黑夜,30; a+b=11
用apply求一个数组的最大值:
var max = Math.max(1,3,4,33,22,66);
var arr=[1,3,4,33,22,66];
var m=Math.max.apply(null,arr);
console.log(m); //66
console.log(max); //66
用call将伪数组转化成数组:
slice方法是用来截取数组中连续的一部分元素,他返回值也是一个数组
slice的用法
var arr=[1,3,4,33,22,66];
var arr2=arr.slice(1,5);
var arr3=arr.slice();
console.log(arr2.toString());//3,4,33,22
console.log(arr2.toString());//1,3,4,33,22,66
将伪数组wsz转换为数组
var wsz = {0:"java",1:"C++",2:"js",length:3};
console.dir(wsz);
var realArr = [].slice.call(wsz);
// var realArr=Array.prototype.slice.call(wsz);//等价于上面的
console.dir(realArr);