我正在寻找将类方法传递给函数的可能性,然后函数可以在该类的实例上执行该函数.像伪代码那样:(注意这是一个抽象的例子)
class Foo {
public somefunc() {
// do some
}
public anyfunc() {
// do any
}
}
function bar(obj: Foo ,func: "Foo.method") { // "that's what im looking for"
obj.func();
}
bar(new Foo(), Foo.somefunc); // do some
bar(new Foo(), Foo.anyfunc); // do any
Run Code Online (Sandbox Code Playgroud)
这样做有可能吗?
我知道我可以这样做:
class Foo {
static somefunc(fooObj: Foo) {
// do some
}
static anyfunc(fooObj: Foo) {
// do any
}
}
interface func {
(fooObj: Foo);
}
function bar(obj: Foo, fn: func) {
fn(obj); …Run Code Online (Sandbox Code Playgroud) 使用Typescript和jQuery时出现问题.元素会附加到正文并显示但单击按钮时没有任何反应.
我想它的this.fooClick()传递给按钮,但没有被调用或错误的jquery元素被保存到类变量.
有人帮吗?
test.ts
/// <reference path="jquery.d.ts" />
class foo {
private button;
private text;
constructor() {
this.button = $('<button>').html("click").click(this.fooClick());
this.text = $('<p>').html("foo");
$('body').append(this.button);
$('body').append(this.text);
}
public fooClick() {
$(this.text).html("bar");
}
}
$(function() {
var foobar = new foo();
})
Run Code Online (Sandbox Code Playgroud)
test.js
/// <reference path="jquery.d.ts" />
var foo = (function () {
function foo() {
this.button = $('<button>').html("click").click(this.fooClick());
this.text = $('<p>').html("foo");
$('body').append(this.button);
$('body').append(this.text);
}
foo.prototype.fooClick = function () {
$(this.text).html("bar");
};
return foo;
})();
$(function () {
var bar = new …Run Code Online (Sandbox Code Playgroud)