面试官出不少考题,基本都会变着方式来考察this
指向,看候选人对JS
基础知识是否扎实。 读者能够先拉到底部看总结,再谷歌(或各技术平台)搜索几篇相似文章,看笔者写的文章和别人有什么不一样(欢迎在评论区评论不一样之处),对比来看,验证与本身现有知识是否有盲点,多看几篇,天然就会完善自身知识。html
附上以前写文章写过的一段话:已经有不少关于
this
的文章,为何本身还要写一遍呢。学习就比如是座大山,人们沿着不一样的路爬山,分享着本身看到的风景。你不必定能看到别人看到的风景,体会到别人的心情。只有本身去爬山,才能看到不同的风景,体会才更加深入。
前端
函数的this
在调用时绑定的,彻底取决于函数的调用位置(也就是函数的调用方法)。为了搞清楚this
的指向是什么,必须知道相关函数是如何调用的。git
非严格模式和严格模式中this都是指向顶层对象(浏览器中是window
)。es6
this === window // true
'use strict'
this === window;
this.name = '若川';
console.log(this.name); // 若川
复制代码
// 非严格模式
var name = 'window';
var doSth = function(){
console.log(this.name);
}
doSth(); // 'window'
复制代码
你可能会误觉得window.doSth()
是调用的,因此是指向window
。虽然本例中window.doSth
确实等于doSth
。name
等于window.name
。上面代码中这是由于在ES5
中,全局变量是挂载在顶层对象(浏览器是window
)中。 事实上,并非如此。github
// 非严格模式
let name2 = 'window2';
let doSth2 = function(){
console.log(this === window);
console.log(this.name2);
}
doSth2() // true, undefined
复制代码
这个例子中let
没有给顶层对象中(浏览器是window)添加属性,window.name2和window.doSth
都是undefined
。面试
严格模式中,普通函数中的this
则表现不一样,表现为undefined
。segmentfault
// 严格模式
'use strict'
var name = 'window';
var doSth = function(){
console.log(typeof this === 'undefined');
console.log(this.name);
}
doSth(); // true,// 报错,由于this是undefined
复制代码
看过的《你不知道的JavaScript
》上卷的读者,应该知道书上将这种叫作默认绑定。 对call
,apply
熟悉的读者会类比为:数组
doSth.call(undefined);
doSth.apply(undefined);
复制代码
效果是同样的,call
,apply
做用之一就是用来修改函数中的this
指向为第一个参数的。 第一个参数是undefined
或者null
,非严格模式下,是指向window
。严格模式下,就是指向第一个参数。后文详细解释。
常常有这类代码(回调函数),其实也是普通函数调用模式。浏览器
var name = '若川';
setTimeout(function(){
console.log(this.name);
}, 0);
// 语法
setTimeout(fn | code, 0, arg1, arg2, ...)
// 也能够是一串代码。也能够传递其余函数
// 类比 setTimeout函数内部调用fn或者执行代码`code`。
fn.call(undefined, arg1, arg2, ...);
复制代码
var name = 'window';
var doSth = function(){
console.log(this.name);
}
var student = {
name: '若川',
doSth: doSth,
other: {
name: 'other',
doSth: doSth,
}
}
student.doSth(); // '若川'
student.other.doSth(); // 'other'
// 用call类比则为:
student.doSth.call(student);
// 用call类比则为:
student.other.doSth.call(other);
复制代码
但每每会有如下场景,把对象中的函数赋值成一个变量了。 这样其实又变成普通函数了,因此使用普通函数的规则(默认绑定)。缓存
var studentDoSth = student.doSth;
studentDoSth(); // 'window'
// 用call类比则为:
studentDoSth.call(undefined);
复制代码
call、apply、bind
调用模式上文提到call
、apply
,这里详细解读一下。先经过MDN
认识下call
和apply
MDN 文档:Function.prototype.call()
语法
fun.call(thisArg, arg1, arg2, ...)
复制代码
thisArg
在fun
函数运行时指定的this
值。须要注意的是,指定的this
值并不必定是该函数执行时真正的this
值,若是这个函数处于非严格模式下,则指定为null
和undefined
的this
值会自动指向全局对象(浏览器中就是window
对象),同时值为原始值(数字,字符串,布尔值)的this
会指向该原始值的自动包装对象。
arg1, arg2, ...
指定的参数列表
返回值
返回值是你调用的方法的返回值,若该方法没有返回值,则返回undefined
。
apply
和call
相似。只是参数不同。它的参数是数组(或者类数组)。
根据参数thisArg
的描述,能够知道,call
就是改变函数中的this
指向为thisArg
,而且执行这个函数,这也就使JS
灵活不少。严格模式下,thisArg
是原始值是值类型,也就是原始值。不会被包装成对象。举个例子:
var doSth = function(name){
console.log(this);
console.log(name);
}
doSth.call(2, '若川'); // Number{2}, '若川'
var doSth2 = function(name){
'use strict';
console.log(this);
console.log(name);
}
doSth2.call(2, '若川'); // 2, '若川'
复制代码
虽然通常不会把thisArg
参数写成值类型。但仍是须要知道这个知识。 以前写过一篇文章:面试官问:可否模拟实现JS
的call
和apply
方法 就是利用对象上的函数this
指向这个对象,来模拟实现call
和apply
的。感兴趣的读者思考如何实现,再去看看笔者的实现。
bind
和call
和apply
相似,第一个参数也是修改this
指向,只不过返回值是新函数,新函数也能当作构造函数(new
)调用。 MDN Function.prototype.bind
bind()
方法建立一个新的函数, 当这个新函数被调用时this
键值为其提供的值,其参数列表前几项值为建立时指定的参数序列。
语法: fun.bind(thisArg[, arg1[, arg2[, ...]]])
参数: thisArg 调用绑定函数时做为this参数传递给目标函数的值。 若是使用new
运算符构造绑定函数,则忽略该值。当使用bind
在setTimeout
中建立一个函数(做为回调提供)时,做为thisArg
传递的任何原始值都将转换为object
。若是没有提供绑定的参数,则执行做用域的this
被视为新函数的thisArg
。 arg1, arg2, ... 当绑定函数被调用时,这些参数将置于实参以前传递给被绑定的方法。 返回值 返回由指定的this
值和初始化参数改造的原函数拷贝。
以前也写过一篇文章:面试官问:可否模拟实现JS
的bind
方法 就是利用call
和apply
指向这个thisArg
参数,来模拟实现bind
的。感兴趣的读者思考如何实现,再去看看笔者的实现。
function Student(name){
this.name = name;
console.log(this); // {name: '若川'}
// 至关于返回了
// return this;
}
var result = new Student('若川');
复制代码
使用new
操做符调用函数,会自动执行如下步骤。
- 建立了一个全新的对象。
- 这个对象会被执行
[[Prototype]]
(也就是__proto__
)连接。- 生成的新对象会绑定到函数调用的
this
。- 经过
new
建立的每一个对象将最终被[[Prototype]]
连接到这个函数的prototype
对象上。- 若是函数没有返回对象类型
Object
(包含Functoin
,Array
,Date
,RegExg
,Error
),那么new
表达式中的函数调用会自动返回这个新的对象。
由此能够知道:new
操做符调用时,this
指向生成的新对象。 特别提醒一下,new
调用时的返回值,若是没有显式返回对象或者函数,才是返回生成的新对象。
function Student(name){
this.name = name;
// return function f(){};
// return {};
}
var result = new Student('若川');
console.log(result); {name: '若川'}
// 若是返回函数f,则result是函数f,若是是对象{},则result是对象{}
复制代码
不少人或者文章都忽略了这一点,直接简单用typeof
判断对象。虽然实际使用时不会显示返回,但面试官会问到。
以前也写了一篇文章面试官问:可否模拟实现JS
的new
操做符,是使用apply来把this指向到生成的新生成的对象上。感兴趣的读者思考如何实现,再去看看笔者的实现。
function Student(name){
this.name = name;
}
var s1 = new Student('若川');
Student.prototype.doSth = function(){
console.log(this.name);
}
s1.doSth(); // '若川'
复制代码
会发现这个似曾相识。这就是对象上的方法调用模式。天然是指向生成的新对象。 若是该对象继承自其它对象。一样会经过原型链查找。 上面代码使用 ES6
中class
写法则是:
class Student{
constructor(name){
this.name = name;
}
doSth(){
console.log(this.name);
}
}
let s1 = new Student('若川');
s1.doSth();
复制代码
babel
es6
转换成es5
的结果,能够去babeljs网站转换测试
自行试试。
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Student = function () {
function Student(name) {
_classCallCheck(this, Student);
this.name = name;
}
_createClass(Student, [{
key: 'doSth',
value: function doSth() {
console.log(this.name);
}
}]);
return Student;
}();
var s1 = new Student('若川');
s1.doSth();
复制代码
由此看出,ES6
的class
也是经过构造函数模拟实现的,是一种语法糖。
先看箭头函数和普通函数的重要区别:
一、没有本身的
this
、super
、arguments
和new.target
绑定。 二、不能使用new
来调用。 三、没有原型对象。 四、不能够改变this
的绑定。 五、形参名称不能重复。
箭头函数中没有this
绑定,必须经过查找做用域链来决定其值。 若是箭头函数被非箭头函数包含,则this
绑定的是最近一层非箭头函数的this
,不然this
的值则被设置为全局对象。 好比:
var name = 'window';
var student = {
name: '若川',
doSth: function(){
// var self = this;
var arrowDoSth = () => {
// console.log(self.name);
console.log(this.name);
}
arrowDoSth();
},
arrowDoSth2: () => {
console.log(this.name);
}
}
student.doSth(); // '若川'
student.arrowDoSth2(); // 'window'
复制代码
其实就是至关于箭头函数外的this
是缓存的该箭头函数上层的普通函数的this
。若是没有普通函数,则是全局对象(浏览器中则是window
)。 也就是说没法经过call
、apply
、bind
绑定箭头函数的this
(它自身没有this
)。而call
、apply
、bind
能够绑定缓存箭头函数上层的普通函数的this
。 好比:
var student = {
name: '若川',
doSth: function(){
console.log(this.name);
return () => {
console.log('arrowFn:', this.name);
}
}
}
var person = {
name: 'person',
}
student.doSth().call(person); // '若川' 'arrowFn:' '若川'
student.doSth.call(person)(); // 'person' 'arrowFn:' 'person'
复制代码
DOM
事件处理函数调用<button class="button">onclick</button>
<ul class="list">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<script>
var button = document.querySelector('button');
button.onclick = function(ev){
console.log(this);
console.log(this === ev.currentTarget); // true
}
var list = document.querySelector('.list');
list.addEventListener('click', function(ev){
console.log(this === list); // true
console.log(this === ev.currentTarget); // true
console.log(this);
console.log(ev.target);
}, false);
</script>
复制代码
onclick
和addEventerListener
是指向绑定事件的元素。 一些浏览器,好比IE6~IE8
下使用attachEvent
,this
指向是window
。 顺便提下:面试官也常常考察ev.currentTarget
和ev.target
的区别。 ev.currentTarget
是绑定事件的元素,而ev.target
是当前触发事件的元素。好比这里的分别是ul
和li
。 但也可能点击的是ul
,这时ev.currentTarget
和ev.target
就相等了。
<button class="btn1" onclick="console.log(this === document.querySelector('.btn1'))">点我呀</button>
<button onclick="console.log((function(){return this})());">再点我呀</button>
复制代码
第一个是button
自己,因此是true
,第二个是window
。这里跟严格模式没有关系。 固然咱们如今不会这样用了,但有时不当心写成了这样,也须要了解。
其实this
的使用场景还有挺多,好比对象object
中的getter
、setter
的this
,new Function()
、eval
。 但掌握以上几种,去分析其余的,就天然迎刃而解了。 使用比较多的仍是普通函数调用、对象的函数调用、new
调用、call、apply、bind
调用、箭头函数调用。 那么他们的优先级是怎样的呢。
而箭头函数的this
是上层普通函数的this
或者是全局对象(浏览器中是window
),因此排除,不算优先级。
var name = 'window';
var person = {
name: 'person',
}
var doSth = function(){
console.log(this.name);
return function(){
console.log('return:', this.name);
}
}
var Student = {
name: '若川',
doSth: doSth,
}
// 普通函数调用
doSth(); // window
// 对象上的函数调用
Student.doSth(); // '若川'
// call、apply 调用
Student.doSth.call(person); // 'person'
new Student.doSth.call(person);
复制代码
试想一下,若是是Student.doSth.call(person)
先执行的状况下,那new
执行一个函数。是没有问题的。 然而事实上,这代码是报错的。运算符优先级是new
比点号低,因此是执行new (Student.doSth.call)(person)
而Function.prototype.call
,虽然是一个函数(apply
、bind
也是函数),跟箭头函数同样,不能用new
调用。因此报错了。
Uncaught TypeError: Student.doSth.call is not a constructor
复制代码
这是由于函数内部有两个不一样的方法:[[Call]]
和[[Constructor]]
。 当使用普通函数调用时,[[Call]]
会被执行。当使用构造函数调用时,[[Constructor]]
会被执行。call
、apply
、bind
和箭头函数内部没有[[Constructor]]
方法。
从上面的例子能够看出普通函数调用优先级最低,其次是对象上的函数。 call(apply、bind)
调用方式和new
调用方式的优先级,在《你不知道的JavaScript》是对比bind
和new
,引用了mdn
的bind
的ployfill
实现,new
调用时bind以后的函数,会忽略bind
绑定的第一个参数,(mdn
的实现其实还有一些问题,感兴趣的读者,能够看我以前的文章:面试官问:可否模拟实现JS
的bind
方法),说明new
的调用的优先级最高。 因此它们的优先级是new
调用 > call、apply、bind
调用 > 对象上的函数调用 > 普通函数调用。
若是要判断一个运行中函数的 this
绑定, 就须要找到这个函数的直接调用位置。 找到以后 就能够顺序应用下面这四条规则来判断 this
的绑定对象。
new
调用:绑定到新建立的对象,注意:显示return
函数或对象,返回值不是新建立的对象,而是显式返回的函数或对象。call
或者 apply
( 或者 bind
) 调用:严格模式下,绑定到指定的第一个参数。非严格模式下,null
和undefined
,指向全局对象(浏览器中是window
),其他值指向被new Object()
包装的对象。undefined
,不然绑定到全局对象。ES6
中的箭头函数:不会使用上文的四条标准的绑定规则, 而是根据当前的词法做用域来决定this
, 具体来讲, 箭头函数会继承外层函数,调用的 this 绑定( 不管 this 绑定到什么),没有外层函数,则是绑定到全局对象(浏览器中是window
)。 这其实和 ES6
以前代码中的 self = this
机制同样。
DOM
事件函数:通常指向绑定事件的DOM
元素,但有些状况绑定到全局对象(好比IE6~IE8
的attachEvent
)。
必定要注意,有些调用可能在无心中使用普通函数绑定规则。 若是想“ 更安全” 地忽略 this
绑 定, 你可使用一个对象, 好比ø = Object.create(null)
, 以保护全局对象。
面试官考察this
指向就能够考察new、call、apply、bind
,箭头函数等用法。从而扩展到做用域、闭包、原型链、继承、严格模式等。这就是面试官乐此不疲的缘由。
读者发现有不妥或可改善之处,欢迎指出。另外以为写得不错,能够点个赞,也是对笔者的一种支持。
this
指向考题常常结合一些运算符等来考察。看完本文,不妨经过如下两篇面试题测试一下。 小小沧海:一道常被人轻视的前端JS面试题
从这两套题,从新认识JS的this、做用域、闭包、对象
你不知道的JavaScript 上卷
冴羽:JavaScript深刻之从ECMAScript规范解读this
这波能反杀:前端基础进阶(五):全方位解读this
做者:常以若川为名混迹于江湖。前端路上 | PPT爱好者 | 所知甚少,惟善学。
我的博客
segmentfault
前端视野专栏,开通了前端视野专栏,欢迎关注~
掘金专栏,欢迎关注~
知乎前端视野专栏,开通了前端视野专栏,欢迎关注~
github blog,求个star
^_^~
可能比较有趣的微信公众号,长按扫码关注。也能够加微信 lxchuan12
,注明来源,拉您进【前端视野交流群】。