2018-07-13 js的call,apply,bind

function containsStr(str) {
    return (new RegExp(str,"ig")).test(this);
}

containsStr.call(a,"peoplE")

a="i like beijing and the people around me"
  1. 函数使用全局变量初始化。
objs={aa:this.aaa,name:'yu',func:function(){console.log(this.name + " : " + this.age);}}
Object {aa: 12, name: "yu"}
objs.func()
VM5462:1 yu : undefined
  1. applyh和call可以改变函数内的上下文,即this引用,可以处理一类对象了!
objs.func.apply(obj)
VM5462:1 aa : undefined
  1. 声明函数时的this使用了window对象或者全局对象,但是this对象被重新赋值后就会读取新的对象的属性来使用。
objs={aa:this.aaa,name:'yu'}
Object {aa: 12, name: "yu"}

objs={aa:this.aaa,name:'yu',func:function(){console.log(this.name + " : " + this.aaa);}}
Object {aa: 12, name: "yu"}
objs.func()
VM5462:1 yu : undefined

objs只有aa属性没有aaa属性,所以console输出undefined,因为此时的this是objs;而不是全局对象或window对象。只有访问aa属性才有值12.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容