十:new操作符
1:new操作符是什么
在JavaScript中new操作符是用于创建一个给定构造函数的实例对象
javascript
function Person(name,age){
this.name = name;
this.age = age;
}
Person.protoype.sayName = function (){
console,log(this.name)
}
cost person1 = new Person('Tom',20)
console.log(person1)//Person{name:"Tom",age:20}
t.sayName()//'Tom'
new通过构造函数Person创建出来的实例可以访问到构造函数中的属性
new通过构造函数Person创建出来的实例可以访问到构造函数原型链中的属性
如果增加返回的原始值会怎么样呢
javascript
function Test(name){
this.name = name
return 1
}
const t = new Test('xxx')
console.log(t.name)//'xxx'
可以看出返回值没有什么用
但是返回值变成一个对象会怎么样呢?
javascript
function Test(name){
this.name = name
console.log(this)//test{name:'xxx'}
return { age : 26}
}
const t = new Test('xxx')
console.log(t)//{age:26}
console.log(t.name)//'undefined'
如果构造函数返回一个对象那么返回值会被正常使用
2:new的工作流程
创建一个新的对象obj
将对象与构造函数通过原型链链接起来
将构造函数中的this绑定到新建的对象obj上
根据构建函数的返回类型作为判断,如果是原始值被忽略如果返回对象则正常处理
十一: bind、call、apply区别?如何实现一个bind?
1:作用
call apply bind作用是改变函数执行上下文,也就是改变函数运行时this指向
javascript
var name = "lucy";
var obj ={
name: "martin",
say: function(){
console.log(this.name);
}
};
obj.say();//martin,this 指向obj对象
setTimeout(obj.say,0);//Lucy,this指向window对象
从上面就可以看到say方法输出Martin
但是say放在setTimeout方法中,在定时器中是作为回调函数来执行的,因此回到主栈执行时是在全局执行上下文的环境中执行的,这时候this指向window ,所以输出lucy我们实际需要的是this指向obj对象,这时候就需要该改变this指向了
javascript
setTimeout(obj.say.bind(obj),0);//martin,this指向obj对象
2:区别
apply、call、bind区别于:
三者第一个参数都是this要指向的对象,如果没有这个参数或者参数为null或者undefined,则默认指向全局window
三者都可以传参,但是apply是数组,而call是参数列表,而且apply和call是一次性传如参数,而bind可以分为多次传入
bind 是返回绑定this之后的函数,apply、call则是立即执行
3:实现
修改this指向
动态传递参数
兼容new关键字
javascript
Function.prototype.myBind = function(context){
if(typeof this !=="function"){
throw new TypeError("Error");
}
const args = [...arguments].slice(1),
fn=this;
return function Fn(){
return fn.apply(this instanceof Fn ? new fn(...argumnets):context,args.concat(...arguments));}
}