js 中的this是比较难理解的。这里将介绍this的具体用法。主要是下面的四种方法:
1.作为对象的方法;
2.作为普通函数中;
3.作为构造函数调用;
4.作为Function.prototype.call或者Function.prototype.apply调用;
- 在构造函数中使用(this -> 构造函数本身)
- 作为对象属性时使用(this ->调用属性的对象)
- 作为普通函数时使用(this ->window)
- call,apply,bind(this ->执行的第一个参数)
一、作为对象的方法使用,this指向这个对象;
For Example:
var adou = {
a:1,
getAdou: function() {
console.log( this===adou );//true
console.log( this.a );//1
}
}
adou.getAdou();
二、作为普通函数调用,this,指向全局变量window (浏览器中)
For Example:
window.a = "adou";
function getAd(){
console.log(this.a);//adou
}
getAd();
在举一个容易混淆的函数例子:
For Example2:
window.a = "adou";
var adou = {
a:1,
getAdou: function() {
console.log( this.a );//adou
}
}
var adouTwo = adou.getAdou;//将adou的getAdou方法赋值给了adouTwo后,
//adouTwo就是一个普通函数,在调用这个普通函数时候,this指向的就是全局变量
adouTwo();
三、作为构造函数调用,this的指向是 往下看
构造函数和普通函数差不多一样的。但是在与调用方式 new的区别(new的具体解析下回分解),当用 new 运算符调用函数时,该函数会返回一个对象。一般情况下,构造器里面的this就是指向返回的这个对象。
For Example:
function Ad(){
this.a = "adou";
}
var adou = new Ad();
console.log(adou.a);//adou
但是,如果构造器函数显示的返回一个object类型的对象,new运算最终的结果会返回这个对象;
For Example2:
function Ad(){
this.a = "adou";
return {
a : "Bob"
}
}
var ad = new Ad();
console.log(ad.a);//Bob
四、 Function.prototype.call 或 Function.prototype.apply 调用 this是指: 往下看
这里简单的说call和apply这个方法:一个对象调用另一个对象的成员函数或属性等。在调用call(apply)的时候。可以动态传入 this ,这个this就是我们最终要操作的对象
For Example:
var ad1 = {
name : "adou",
getName : function(){
console.log(this.name)
}
}
var ad2 = {
name : "adou2"
}
ad1.getName();//adou
ad1.getName.call(ad2);//adou2
下方的this 如下:
<script>
var tree = {};
tree.decorate = function () {console.log(333)}
tree.getdeco = function (deco) {
console.log(this,deco)
tree[deco].prototype = this;
return new tree[deco]
}
tree.redBalls = function(){
console.log('1',this);
this.decorate = function (){
console.log('2',this)
this.redBalls.prototype.decorate();
console.log('这是一个decorate')
}
}
tree = tree.getdeco('redBalls');
tree.decorate()
</script>