JavaScript的this在不同环境下指向

    技术2026-08-04  25

    JavaScript的this指向

    this在不同环境下指向函数调用多层对象调用构造函数调用箭头函数调用 绑定this指向

    this在不同环境下指向

    事件调用环境: 谁触发事件,函数里面的this指向就是谁 全局环境: window;module.exports(node)

    函数调用

    this最终指向调用它的对象 var obj = { method: { fn: function() { console.log(this); }, fun: function() { console.log(this); } } } var fun = obj.method.fn; fun(); //=window.fun() 所以指向window window.obj.method.fn(); //指向method,参考下一个知识点

    多层对象调用

    函数被多层对象所包含,如果函数被外层对象调用,this指向的也只是它上一级的对象 var obj = { method: { fn: function() { console.log(this); }, fun: function() { console.log(this); } } } obj.method.fn(); //method window.obj.method.fn(); //method

    构造函数调用

    如果构造函数中有return,this指向返回的对象,如果不是对象,this指向则保持原来的规则,null比较特殊的一个对象 function fun(){ this.x="this text"; //return ""; out:"this text" //tetrun []; out:undefined //return {}; out:undefined //return 1; out:"this text" //return null; out:"this text" return {}; } var obj =new fun(); console.log(obj.x)

    构造函数

    new fun() new运算符所做的事情: 1.调用函数 2.自动创建一个对象 3.把创建出来的对象和this进行绑定 4.如果构造函数没有返回值,隐式返回this对象

    综合案例

    function fun(){ this.value = 10; } fun.value = 20; fun.prototype.value = 30; fun.prototype.method = function(){ console.log(this.value); } //prototype 属性使您有能力向对象添加属性和方法。 var prototype = fun.prototype; var method = prototype.method; new fun().method(); //10 prototype.method(); //30 var value = 100; method(); //100 该方法指向window

    箭头函数调用

    箭头函数本身没有this和arguments,在箭头函数中引用this实际上调用的是定义是的上一层作用域的this。 var obj = { fun: () => { console.log(this); } } obj.fun(); //window var obj1 = { fun: function() { console.log(this); } } obj1.fun(); //obj1

    绑定this指向

    call apply bind 代码实现

    var box = document.querySelector(".box"); var x,y; //传参变量 var obj = { fn : function(){//此处不能使用箭头函数 console.log(this); } } obj.fn.call(box,x,y); obj.fn.apply(box,[x,y]); obj.fn.bind(box,x,y)();
    Processed: 0.059, SQL: 10