面试官的小久久

前言
这几次面试的是工资略微高的,也就是说不是初级前端了,我发现这些企业技术负责人都不用我再去写面试题了,可能是人家觉得你都面试中高级了,基础就不考试你了吧。
下边是面试经过被问到的

面试题
讲解一下Function.prototype.bind()的认知?

打开火狐的js文档你会发现,js内置(类)对象Function,有3个自己的(静态)原型方法。碰巧的是这3个方法,均与函数内部的上下文this有关。
call、apply、bind都是为了改变某个函数运行时的上下文而存在的,也就是改变函数内部this的指向,
当然都可以借助此特性来实现es6之前的继承,在特定的作用域中调用这些方法,能改变制定函数的作用域,实际上是改变函数体内 this 的值 。

改变函数作用域,修改函数运行时的this指针

function People(name){
    this.name=name;
    this.say=function (time,msg) {
        console.log(time+':'+this.name+'说'+msg)
    }
}

var xm=new People('小明');
var xh=new People('小红');

//用call实现
xm.say.call(xh,2018,'你好啊')

//用apply
xm.say.apply(xh,[2018,'你好啊'])

//用bind
xm.say.bind(xh)(2018,'你好啊')
View Code


实现继承

function People(){
    this.say=function () {
        console.log(this.name+'说:我是人类')
    }
}

//利用call实现继承
function Stu(name) {
    People.call(this)//会执行一遍People内部代码,其中执行的上下文对象是这个函数的this,本质上相当于把People内代码copy到Stu里边
    this.name=name
    this.test=function () {
        console.log('测试')
    }
}
stu.say()
stu.test()
View Code
function People(){
    this.say=function () {
        console.log(this.name+'说:我是人类')
    }
}

function Stu(name) {
    this.name=name
    this.test=function () {
        console.log('测试')
    }
    // People.bind(this)()//写法二

}

var stu=new Stu('小明');
People.bind(stu)()// 写法一:函数A.bind(对象a)(arg)这样的话,函数A内部的调用对象就是对象a了,这样写法有点死板,写法2是动态的
stu.say()
stu.test()
View Code




 

猜你喜欢

转载自www.cnblogs.com/dshvv/p/9855555.html