查看“︁JavaScript/typescript/回调函数”︁的源代码
来自康健生活
←
JavaScript/typescript/回调函数
因为以下原因,您没有权限编辑该页面:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
== 引言 == 在每个页面的 <code>methods</code> (VUE.js) 对象中,我需要定义一个在走后端接口之前,校验一下登录状态的功能,代码如下: <syntaxhighlight lang="javascript"> import {whetherNoLogin} from '@@/plugins/util.ts'; /* 判断用户是否登录 */ if(whetherNoLogin(this.$store.state.user, this.$message)){ return false }</syntaxhighlight> 函数定义如下: {{hc|head=@@/plugins/util.ts|output=<syntaxhighlight lang="typescript"> /** * 验证登陆状态 * @param user * @param $message */ export function whetherNoLogin(user:{token: string|undefined|null}, $message: (arg:object) => void): boolean{ if(user && user.token){ return false }else{ $message({ message: '请先登录', type: 'warning', duration: '2000' }); return true } } </syntaxhighlight>}} 其中回到函数如果使用内联,则 <code>(arg:object) => void)</code> == 类型 == 声明回调函数类型: <syntaxhighlight lang="javascript"> event.on('change', function() {}); </syntaxhighlight> <syntaxhighlight lang="typescript"> type CB = () => void; on(type: string, cb: CB);</syntaxhighlight> == this == 老生常谈的 this 指向问题 === 示例 === {{hc|head=TestCallAndThis.ts|output=<syntaxhighlight lang="typescript"> namespace naiking { /** *author : NaiKing *description: */ export class TestCallAndThis { /** * 不推荐的回调写法 * 外部调用必须【必须】【必须】在回调参数方法后面添加.bind(this), * 否则可能会this异常 */ public static callBackTest(arg:number,callBack:Function):void { //返回 2 x arg let result:number=arg*2; //不推荐直接调用回调方法,应使用callBack.call(caller,result); callBack(result); } /** * 推荐的回调写法 * @param arg 参数 * @param caller 调用域 * @param method 指定的回调方法(兼容.bind(this) 也可以不加.bind(this) ) */ public static callMethod(arg:number,caller:any,method:Function):void { //返回 2 x arg let result:number=arg*2; //推荐的做法 .call(caller,result); method.call(caller,result); } } } </syntaxhighlight>}} {{Unknown|https://www.cnblogs.com/naiking/p/9836289.html}} {{hc|head=测试.ts|output=<syntaxhighlight lang="typescript"> namespage naiking { export class Luna { //注意观察,this异常的时候的isLoading的值是undefind private isLoading:boolean = false; private getResult(rst:number):void { console.log("get rusult:"+rst+this.isLoading); } constructor() { //不推荐的回调写法, 遗漏了bind(this) logic.TestCallAndThis.callBackTest(1,this.getResult); //不推荐的回调写法, 使用了bind(this)( √ ) logic.TestCallAndThis.callBackTest(1,this.getResult.bind(this)); //提倡的回调写法 ,有无bind(this)都可以 logic.TestCallAndThis.callMethod(1,this,this.getResult); logic.TestCallAndThis.callMethod(1,this,this.getResult.bind(this)); } }} </syntaxhighlight>}} {{Unknown|https://www.cnblogs.com/naiking/p/9836289.html}} == 参考 == * https://stackoverflow.com/questions/29689966/typescript-how-to-define-type-for-a-function-callback-as-any-function-type-no
此页面嵌入的页面:
模板:Hc
(
查看源代码
)
模板:Hc/style.css
(
查看源代码
)
模板:Unknown
(
查看源代码
)
返回
JavaScript/typescript/回调函数
。
导航菜单
康健生活
搜索
user-page
通知
user-interface-preferences
个人工具
登录
五一
多读书,多运动,多到远处走走,再看看不一样的世界。