×

This - javascript面向对象编程

作者:jiang2017.10.10来源:Web前端之家浏览:8089评论:0
关键词:this

This - 面向对象编程。

1.全局环境下,this === window,如:

console.log(this === window);

2.构照函数中的this,指的是实例对象,如

var obj = function(p){
    this.p = p;
}
obj.prototype.getP = function(){
    return this.p;
}
var o = new obj("Hello World!");
console.log(o.p);
>>> Hello World!
console.log(o.getP());
>>> Hello World!

注意点

1. 避免多层使用this

var obj = {
    f1:function(){
        console.log(this);
        var f2 = function(){
            console.log(this);
        }();
    }
}
obj.f1();
>>> Object
    Window

上面代码包含两层this,结果运行后,第一层指向该对象,第二层指向全局对象。
如何修改?改用一个指向外层this的变量_that

var obj = {
    f1:function(){
        console.log(this);
        var _that = this;
        var f2 = function(){
            console.log(_that);
        }();
    }
}
obj.f1();
>>> Object
    Object

2. 避免数组处理方法中的this

var obj = {
    v:'hello',
    p:['a1','a2'],
    f: function f(){    
        this.p.forEach(function(item){
            console.log(this.v + ' ' + item);
        });
    }
}
obj.f();
>>> undefined a1
    undefined a2

出现undefined的原因是forEach方法的回调函数中的this,其实是指向window对象,因此取不到obj.v的值
解决方法一:使用中间变量。

var obj = {
    v:'hello',
    p:['a1','a2'],
    var _that = this;
    f:function f(){
        this.p.forEach(function(item){
            console.log(_that.v + ' ' + item);
        });
    }
}
obj.f();
>>> hello a1
    hello a2

解决方法二:将this当作foreach方法的第二个参数。

var obj = {
    v:'hello',
    p:['a1','a2'],
    f:function f(){
        this.p.forEach(function(item){
            console.log(this.v + ' ' + item);
        },this);
    }
}

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/js123ssssss.html

网友评论文明上网理性发言 已有0人参与

发表评论: