0
点赞
收藏
分享

微信扫一扫

this常用的用法

1.函数作为对象的方法时,this指的是该对象;
var obj ={
name:"bob",
age:25,
getName:function(){
console.log(this.name) ------->//bob
}
}
obj.getName();

2.局部函数里的this指的是window对象
var age=30;
var obj ={
name:"bob",
age:25,
getAge:function(){
function aa(){
console.log(this.age) ------->//30
}
aa();
console.log(this.age) ------->//25
}
}
obj.getAge();

3.构造函数动态this
function Car(name,price){ //构造函数
this.name = name;
this.age = age;
this.date = "2016.03.02";
}

Car.prototype.start = function(){
console.log(this.name + "定义函数对象的方法一")
}

Car.prototype.end = function(){
console.log(this.name + "定义函数对象的方法二")
}

Car.prototype.getPrice = function(){
console.log(this.price + "定义函数对象的方法三") //this指动态绑定对象 的实例(obj1,obj2谁做的)
}

var obj1 = new Car("宝马",1000000) -------->创建一个新的对象
var obj2 = newCar("奥迪",400000) -------->再创建一个对象分配另一个实例
obj1.getPrice(); -------->//它调用时候是1000000
obj2.getPrice(); -------->//它调用时候是400000

4.this的链式调用
function Car(name,price){ //构造函数
this.name = name;
this.age = age;
this.date = "2016.03.02";
}

Car.prototype.start = function(){
console.log(this.name + "定义函数对象的方法一")
return this;
}

Car.prototype.end = function(){
console.log(this.name + "定义函数对象的方法二")
return this;
}

Car.prototype.getPrice = function(){
console.log(this.price + "定义函数对象的方法三") //this指动态绑定对象 的实例(obj1,obj2谁做的)
return this;
}

var obj1 = new Car("宝马",1000000) -------->创建一个新的对象
var obj2 = newCar("奥迪",400000) -------->再创建一个对象分配另一个实例
obj1.getPrice(); -------->//它调用时候是1000000
obj2.getPrice(); -------->//它调用时候是400000

obj1.getPrice().start().end(); -------->//它调用了三个方法,是通过retur this来实现!!!

如果函数直接调用如 aa();默认this为window对象;

 



举报

相关推荐

0 条评论