Javascript 基础之this关键字

首先梳理下函数调用的几种方式:

调用方式 表达式
构造函数调用 new Student
对象方法调用 student.getName()
函数直接调用 getName()
call/ apply/ bind function.call(obj)
构造函数调用
function Student (name, age){
    this.name = name;
    this.age = age;
}
var stu = new Student("Spursyy", 18);
console.log(stu);
对象方法调用
function Student (name, age){
    this.name = name;
    this.age = age;
    this.getName = function() {
        console.log(this.name);
    };
}
var stu = new Student("Spursyy", 18);
stu.getName();
函数直接调用
function multiply (x, y) {
    return x * y;
}
var result = {
    value: 3,
    total: function () {
         return function getTotal() {
            this.value = multiply(this.value, this.value);
        };
    }
};
console.log(result.value);  // 3
result.total();
console.log(result.value);  // 3

为什么第二个输出是3,而不是9. 经debug 发现函数内部创建函数,当调用这个函数时,this指向windows 而不是外部函数。

解决方案1,
 // 取消内部函数
    total2: function() {
        return this.value = multiply(this.value, this.value);
    },
解决方案2,
// 保存外部函数this
    total3: function() {
        var that = this;
        return function getTotal() {
            that.value = multiply(that.value, that.value);
        }; 
    }
使用 call/apply与bind 改变 this的指向
function Point (x, y){
    this.x = x;
    this.y = y;
}
Point.prototype.move = function (addX, addY) {
    this.x += addX;
    this.y += addY;
}
var point = new Point(0,0);
console.log(point);
point.move(2,3);
console.log(point);

var circle = {x: 0, y: 0, r: 2};
//apply 后面的参数是数组
point.move.apply(circle, [1,2]);  //{x; 1, y: 2, r : 2}
//call 后面的参数是多个常量
point.move.call(circle, 1, 2);   //{x; 2, y: 4, r : 2}
console.log(circle);

call/ apply 可以让circle 没有构造函数原型上没有定义move的函数,却可以实现move的函数作用,因此具有扩展作用域的作用。

bind/apply 虽然可以改变this指向,但是每次执行都要调用函数bind/apply,ES5定义了bind 函数永远改变this的指向。

var circleMove = point.move.bind(circle, 1,3 );
circleMove(3,3);
    VS
var circleMove = point.move.bind(circle);
circleMove(3,3);

point.move.bind(circle, 1,3 ); 永久的将(1, 3) 绑定在circleMove 的函数上,即使后面传参数也不能生效。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容