您当前的位置: 首页 >  Java

暂无认证

  • 0浏览

    0关注

    92582博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

JavaScript之this指向

发布时间:2022-01-19 14:24:53 ,浏览量:0

目录
  • 01、(b = person.thisPoint)(); => b();
  • 02、改变this指向之bind、call、apply的优先级
  • 3、函数调用时前面有点
  • 4、this指向全局和对象
  • 5、指向新对象
  • 6、显示绑定、apply、call、bind
01、(b = person.thisPoint)(); => b();
var variable = 'window', person = { variable: 'person', thisPoint: function() { console.log(this.variable); }, }; function thisPoint() { var sss = person.thisPoint; sss(); // window // 因为执行前没有点 // 所以this指向全局 person.thisPoint(); // person // 调用前有点 // 点前是谁,this就指向谁 (b = person.thisPoint)(); // window // (b = ƒ () { console.log(this.variable); })(); // b(); // 因为调用前没有点 // 所以this指向window全局 } thisPoint(); 
02、改变this指向之bind、call、apply的优先级

显式绑定(bind > call = apply)> 隐式绑定 > 默认绑定

function thisPoint() { console.log(this.name); } var obj1 = { name: 'obj1' }, obj2 = { name: 'obj2' }; thisPoint.bind(obj1); // 没有打印 // 说明bind是预先绑定 // 不会立即执行 thisPoint.bind(obj1)(); // obj1 var fn = thisPoint.bind(obj1); fn(); // obj1 fn.call(obj2); // obj1 // 说明bind的优先级高于call thisPoint.call(obj2); // obj2 // 创建新的堆内存 // 与之前的bind绑定互不干扰 thisPoint.bind(obj2)(); // obj2 thisPoint.call(obj1); // obj1 
3、函数调用时前面有点
var myObject = { value: 7 }; myObject.getValue = function () { console.log(this.value); // 7 console.log(this); // {value: 7, getValue: ƒ} // 函数调用前有点 // 所以this指向myObject return this.value; }; console.log(myObject.getValue()); // 7 
4、this指向全局和对象
var myObject = { value: 7 }; myObject.getValue = function () { var foo = function () { console.log(this.value); // undefined // 函数调用前没有点 // this指向全局 console.log(this); // Window {window: Window, self: Window, document: document, name: '', location: Location, …} // 与上同 }; foo(); return this.value; }; console.log(myObject.getValue()); // 7 
5、指向新对象
var SomeClass = function () { this.value = 7; } var myCreate = new SomeClass(); // 此处相当于创建了一个新对象 console.log(myCreate.value); // 7 
6、显示绑定、apply、call、bind
var myObject = { value: 7 }; var foo = function () { return this; }; console.log(foo()); // Window {window: Window, self: Window, document: document, name: '', location: Location, …} // 函数调用前没有点 // this指向全局 console.log(foo.apply(myObject)); // {value: 7} console.log(foo.call(myObject)); // {value: 7} console.log(foo.bind(myObject)()); // {value: 7} // bind不会立即执行 // 所以在末尾加圆括号执行 
关注
打赏
1653961664
查看更多评论
立即登录/注册

微信扫码登录

0.4479s