JavaScript/typescript/回调函数:修订间差异
来自康健生活
创建页面,内容为“== 引言 == == this == 老生常谈的 this 指向问题 === 示例 === {{hc|head=TestCallAndThis.ts|output=<syntaxhighlight lang="typescript"> namespace naiking {…” |
|||
| (未显示同一用户的2个中间版本) | |||
| 第1行: | 第1行: | ||
== 引言 == | == 引言 == | ||
在每个页面的 <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 == | ||
老生常谈的 this 指向问题 | 老生常谈的 this 指向问题 | ||
| 第67行: | 第106行: | ||
</syntaxhighlight>}} | </syntaxhighlight>}} | ||
{{Unknown|https://www.cnblogs.com/naiking/p/9836289.html}} | {{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 | |||