js 函数中的this
JS 函数 this
2023-09-14 08:58:45 时间
function 函数
没有“this”的持久概念, 调用函数时,创建this
function hello(thing) {
console.log(this + " says hello " + thing);
}
person = { name: "Brendan Eich" }
person.hello = hello;
// 在person中调用 hello, this被创建到了person
person.hello("world") // still desugars to person.hello.call(person, "world")
// 在window中调用 this被创建到了 window
hello("world") // "[object DOMWindow]world"
引用具有持久this值的函数
name = "global";
var person = {
name: "Brendan Eich",
hello: function() {
console.log(this.name);
}
};
var boundHello = function(arguments) {
return person.hello.apply(person, arguments);
};
boundHello(); // Brendan Eich
let a = person.hello.bind(person);
a(); // Brendan Eich
let b = person.hello
b() // global
箭头函数
箭头函数捕获this => 创建函数的位置 而不是调用它的位置
箭头函数没有自己的
this
, 箭头函数内部的上下文在函数的整个生命周期中保持不变, 并且始终将this绑定到最接近的非箭头父函数中的上下文
let o = {
a: 'ajanuw',
hello: function(){
// 返回箭头函数时,this已经被绑定了
return () => {
console.log(this.a)
}
}
}
let a = o.hello()
a()
相关文章
- JS常用自定义函数总结
- JS框架_(JQuery.js)Tooltip弹出式按钮插件
- JS框架_(JQuery.js)动画效果鼠标跟随
- JS框架_(Vue.js)带有星期日期的数字时钟
- js函数前加分号和感叹号的作用
- three.js之让物体动起来方式(一)移动摄像机
- js String Trim函数
- JS判断只能是数字和小数点
- [Node.js] Mock an API for Local Development in React with Mirage JS
- [Tools] Install and Manage Node.js Versions with nvm
- When.js的原理及快速实现
- js事件处理函数中return的作用
- js日期格式化函数示例:将日期时间格式化成yyyy-mm-dd hh:ii:ss格式
- atitit.系统托盘图标的设计java swing c# .net c++ js
- 华为OD机试 - 几何平均值最大子数组(Java & JS & Python)
- 第68篇 QML 之 详解 JS 对象中的函数与this对象
- Ios开发之 -- js和ios的交互
- js调用百度地图接口绘制任意多边形并获取每个点的经纬度等
- JS:使用Mock.js生成随机数据,拦截 Ajax 请求
- js函数与对象关系快速记忆
- js准确获取当前页面url网址信息
- js的StringBuffer实施和使用类
- JS 高级(一)RegExp、函数、重载、作用域和作用域链
- Node.js(一)概述、全局对象/函数、node各模块使用介绍
- js常用的7种函数总结
- 【JS高级】js面向对象三大特性之多态_07
- selenium框架操作stealth.min.js文件隐藏浏览器指纹特征