【JavaScript】this指的是谁?
文章目录
在函数创建的时候,函数内部自动获取到this(还有一个arguments)。this引用的是函数功能据以执行的环境对象,因此this的值与调用函数的方式有着密切的关系。
-
作为函数调用时,
this指向window。var name = 'window'; function sayName() { console.log(this.name); } sayName(); //window -
作为对象的方法调用时,
this指向该对象。var obj = { name: 'object', sayName: function() { console.log(this.name); } }; obj.sayName(); //object (obj.sayName = obj.sayName)(); //window (obj.sayName, obj.sayName)(); //window赋值语句和逗号运算符都会返回后面变量的值,所以后两者相当于在全局中调用了函数,
this指向了window。 -
调用构造函数
在调用构造函数时返回this,this指向构造函数;创建的实例中,this指向实例对象。function Person(n) { console.log(this); this.name = n; this.sayName = function() { return this.name; }; } var person = new Person('hiyohoo'); //Person{} console.log(person.sayName()); //hiyohoo -
调用函数时指定
this。在调用函数时如果使用函数方法call()、apply()、bind()。则函数内部的this指向方法指定的对象。而一旦被bind()指定了this值,之后不管以何种方式调用函数,其this值始终指向bind()指定的对象环境。var outer = { name: 'outer', inner: { name: 'inner', t: function() { return this.name; } } }; console.log(outer.inner.t()); //inner console.log(outer.inner.t.bind(outer)()); //outer -
闭包中的
this。若闭包在全局作用域中调用,则this指向window。这里我们用定时器做例子:var name = 'window'; var obj = { name: 'object', sayName: function() { setInterval(function() { console.log(this.name); }, 1000); } }; obj.sayName(); //window 作为
dom绑定事件的回调函数。this指向这个dom元素。
转载请注明出处:https://segmentfault.com/a/1190000004587440
文章不定期更新完善,如果能对你有一点点启发,我将不胜荣幸。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论