try catch finally this
try {
// throw 1;
// throw new Number(2)
// throw new String('uiop')
// throw ('uiop')
// throw null;
// throw undefined;
// throw {};
// throw ()=>1;
throw Error('new error')
// throw ReferenceError('reference error')
// throw new ReferenceError('Ref Error')
// throw [1,2,3]
// throw new Array(1,2,3)
// throw {'a':22}
} catch (error) {
console.log(error)
console.log(typeof error)
console.log(error.constructor.name)
} finally {
console.log('+++++end=========')
}
var s = {
name: 'uioop',
getNameFunc: function () {
console.log(this.name)
console.log(this)
console.log(this === global)
return function (bb) {
console.log(this === global);
console.log(bb)
return this.name;
}
}
}
method=s.getNameFunc
b=method.call(s)
console.log(b())
console.log('@@@@@@@@')
console.log(b.call(s,789))
// console.log(s.getNameFunc()())
函数执行时,会开启新的执行上下文环境ExecutionContext
会创建this属性,但是this是什么,就要看函数的调用方式
- myFunction(1,2),普通调用方式,this指向global对象, nodejs的global 或者浏览器的window
- myObject.myFunction(1,2),对象的调用方式,this指向包含该方法的对象
- call & apply方法调用,取决于第一参数
需要明确的让this必须是我们期望的对象,如何解决
- 显式传入
var s = { 'name': 'uiop', 'getNameFunc': function () { console.log(this.name); console.log(this); console.log(this === global); console.log('~~~~~~~~~~~~~~~~~~~'); return function (that) { console.log(this) console.log(that === global); console.log(that) return that.name } } } console.log(s.getNameFunc()(s))
this依然指向global,this为保留参数,关键字
- call apply
var s = {name: 'uiop',getNameFunc: function () {console.log(this.name)console.log(this)return function (x,y,z) {console.log(this===global,x,y,z)return this.name}}}b=s.getNameFuncbb=b.apply(s)// console.log(bb.apply(s,[1,2,3])) // apply 传arrayconsole.log(bb.call(s,1,2,3)) // call 传参数call apply 方法都是函数对象方法,第一参数都是传入对象引入
apply传其它参数需要使用数组
call传其它参数需要使用可变参数收集function Print(){ this.print=function(x,y){console.log(x-y,this)} console.log(this) } p=new Print(1,2) console.log(p,typeof p) p.print(1,22) p.print.apply(p,[22,33]) p.print.call(p,22,33.4) b=p.print b(2,3) // console.log(Print()) // console.log(this)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律