this是什么
this是Javascript语言的一个关键字它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。
this的指向
this就是谁调用我 我指向谁
1、以函数形式调用时,this是window;
2、以方法的形式调用时,this是调用方法的那个对象;
3、以构造函数的形式调用时,this是创建的那个对象;
4、使用call和apply调用时,this是指定的那个对象。
改变this指向的方法
一、call
function Animal(){
this.name="cat";
this.showName=function(str){
alert(str+this.name);
}
}
function Cat(){
this.name="Cat";
}
var animal=new Animal();
// animal.showName("dog");//dogcat
// animal.showName("这是一只快乐的")//这是一只快乐的cat
var cat=new Cat();
animal.showName.call(cat,"这是一只快乐的");//这是一只快乐的Cat
function sub(){
this.showSub=function(a,b){
alert(a-b)
}
}
function add(){
this.showAdd=function(a,b){
alert(a+b)
}
}
//sub.call(add,30,20);//50
function mid(){
sub.call(this);
add.call(this);
}
var mid=new mid();
mid.showAdd(30,20);//50
mid.showSub(30,20);//10
二、apply
// 父类
function Person(name,age){
this.name=name;
this.age=age;
}
// 子类 学生
function Student(name,age,grade){
// Person.call(this,name,age);
Person.apply(this,arguments);//子类继承了父类
this.grade=grade;
}
var s1=new Student("张三","23","景秀教育毕业","一年级");
console.log("您好,",s1.name,"您今年",s1.age,"岁,就读于",s1.grade,",实在太棒了")
三、bind
function fn(x, y) {
console.log(this);
}
var obj = {
name: "zs"
}
fn(1, 2);
fn.bind(obj, 1, 2)();