手写instanceof
出题目的
- 考察原型链的理解
知识点
instanceof
1. instanceof运算符用于检测构造函数的prototype属性是否出现在某个实例对象的原型链上
2. 可以判断继承关系,只要是在同一条原型链上,就可以返回true
参考答案
while (true) {
if (obj1Proto === null) {
return false;
} else if (obj1Proto === obj2Prototype) {
return true;
}
obj1Prto = obj1Proto.__proto__;
}
this不同场景,如何取值
this 易混场景
- 普通函数下的this
- call apply bind的this
- 定时器中的this
- 箭头函数中的this
测试题
let obj = {
x: 123,
show() {
setTimeout(() => {
console.log(this.x);
}, 100);
},
};
obj.show();
obj.show.call({x:100})
let obj = {
fn: () => {
console.log(this, 999);
},
};
obj.fn();
演示代码
情况1:
o 是 new 实例化来的,有单独的作用域
class Obj {
say = () => {
console.log(this);
};
}
const o = new Obj();
o.say();
const oBtn = document.getElementById("btn");
oBtn.onclick = function () {
console.log(this);
};
手写bind函数
知识点
- Funciton.prototype.myBind
- Arrat.prototype.slice.cell()
- array.shift()
演示代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@说人话的前端 - bilibili</title>
</head>
<body></body>
<script>
function fn(a, b, c, d) {
console.log(this);
console.log(a, b, c, d);
return "this is return";
}
Function.prototype.myBind = function () {
const fn = this;
const arg = Array.prototype.slice.call(arguments);
const _this = arg.shift();
return function () {
return fn.apply(_this, arg);
};
};
const cb = fn.myBind({ x: 300 }, 1, 2, 3, 4);
console.log(cb());
</script>
</html>
谈谈闭包和闭包使用场景
什么是闭包
- 概念:闭包是作用域的一种特殊应用
触发闭包的情况
- 函数当返回值被返回
- 函数当参数传递
- 自执行匿名函数
闭包的应用
- 隐藏变量
- 解决for i 的问题
作用域
- 全局作用域,局部作用域
自由变量
- 不在自己作用域里的变量,就是自由变量
- 自由变量的值,在函数定义的地方上层作用域查找,与函数调用位置无关
演示代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@说人话的前端 - bilibili</title>
</head>
<body></body>
<script>
(function (index) {
console.log(index);
})(10);
</script>
</html>