js this指向以及

javascript 中 this的指向情况

this指向被调用时的命名空间
1、一般情况下:this = window
2、函数中的this为函数调用时的运行环境,一般时window
3、对象的属性方法,this指向该对象
4、使用call、apply、bind时指定的的对象为this
5、()=>{} 箭头函数的this指向其所在环境的环境变量
6、new 关键字 new Constructor()

javascript中改变this指向的方法

function sum(x, y) {
    return x + y + this.z;
}

1、call(this[,arg1[,arg2]])

sum.call({ z: 3 }, 1, 2); //6

2、apply(this,[…arguments])

sum.apply({ z: 3 }, [1, 2]) //6

3、bind(arg1[,arg2[,arg3]]) bind([…arguments])([…arguments])

sum.bind({z:3},1)(2); //6

在这里插入图片描述
4、new

function Student(age) {
    this.name = 'name';
    this.age = age;
    this.setname = function (name) {
        this.name = name;
    }
    this.getname = function () {
        console.log(this.name);
    }
}
var st=new Student(20);
st.setname('小明'); 
st.getname() //小明

5、箭头函数

由于箭头函数不绑定this, 它会捕获其所在(即“定义”的位置)上下文的this值, 作为自己的this值(箭头函数里面调用this是其在定义时所处环境的‘命名空间’)
() => {} item => console.log(item);
翻译
function (){} function(item){ console.log(item); }

下面是箭头函数在不同情况下的this指向:

var name = 'window.name全局';
var obj = {
    name: '箭头函数',
    getName: () => {
        console.log(this.name);
    }
}
//obj.getName() === "window.name全局"

var Student=(age)=>{
    this.age = age;
    this.setAge = (data) => {
        this.age = data;
    }
}
//Uncaught TypeError: Student is not a constructor

Array.prototype.getlength = (data) => {
   console.log(this === window); //true
    return this.length;
}
var array=new Array([12,13]);
//array.getlength() === undefined

this指向引申问题

不能使用箭头函数的情况

1、对象的属性方法:无法获得当前对象的属性值
2、构造函数:this指向其定义上下文,new的过程中依然无法指向新生成的对象
3、原型链上添加方法:this始终指向其定义上下文,无法获取新生成对象原型链上的属性

js源码实现bind功能

Function.prototype.bind = function (content) {
    var self = this,
        args = Array.from(arguments);
    return function () {
        var innerArgs = Array.from(arguments);
        var finalArgs = args.concat(innerArgs);
        return self.apply(content, finalArgs);
    }
}

function sum(x, y, z) {
    return x + y + z;
}
var a = sum.bind(1, 2, 3)();
var b = sum.bind(1)(2, 3);
a;b;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值