我认为这是使用TS实现方法别名的最简单方法:
export class Foo {
bar(){
}
aliasOfBar(){
return this.bar.apply(this, arguments);
}
}
但我只是想知道是否还有另一种方法可以用TS(或JS)定义别名。也许理想情况下没有额外的函数调用。
如果我这样做,例如:
let mySharedFn = function () {
};
export class Foo {
public bar = mySharedFn
public aliasBar = mySharedFn
}
它转化为:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var mySharedFn = function () {
};
var Foo = (function () {
function Foo() {
this.bar = mySharedFn;
this.aliasBar = mySharedFn;
}
return Foo;
}());
exports.Foo = Foo;
我想避免使用构造函数创建方法等附带的额外调用。
答案 0 :(得分:5)
您可以使用接口和原型将别名方法添加到类中,如下所示:
class Person {
constructor(public name: string) {}
greet(greeting: string): string { return `${greeting}, ${this.name}`; }
}
interface Person {
hi: typeof Person.prototype.greet;
}
Person.prototype.hi = Person.prototype.greet;
const p = new Person("Alice");
console.log(p.greet("Hey"));
console.log(p.hi("Hi"));
答案 1 :(得分:1)
也许是绑定或引用的东西:
export class Foo {
public bar() {}
public aliasBar = this.bar.bind(this);
public aliasGreetSecond;
constructor() {
this.aliasGreetSecond = this.bar;
}
}
上述内容将转化为:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Foo = (function () {
function Foo() {
this.aliasBar = this.bar.bind(this);
this.aliasGreetSecond = this.bar;
}
Foo.prototype.bar = function () { };
return Foo;
}());
exports.Foo = Foo;
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
在TypeScript playground中测试: https://www.typescriptlang.org/play/
class Greeter {
greeting: string;
aliasGreetSecond;
constructor(message: string) {
this.greeting = message;
this.aliasGreetSecond = this.greet;
}
greet() {
return "Hello, " + this.greeting;
}
aliasGreet = this.greet.bind(this);
}
let greeter = new Greeter("world");
let button = document.createElement('button');
let button2 = document.createElement('button');
button.textContent = "With bind";
button.onclick = function() {
alert(greeter.aliasGreet());
}
button2.textContent = "With reference";
button2.onclick = function() {
alert(greeter.aliasGreetSecond());
}
document.body.appendChild(button);
document.body.appendChild(button2);
这将转化为:
var Greeter = /** @class */ (function () {
function Greeter(message) {
this.aliasGreet = this.greet.bind(this);
this.greeting = message;
this.aliasGreetSecond = this.greet;
}
Greeter.prototype.greet = function () {
return "Hello, " + this.greeting;
};
return Greeter;
}());
var greeter = new Greeter("world");
var button = document.createElement('button');
var button2 = document.createElement('button');
button.textContent = "With bind";
button.onclick = function () {
alert(greeter.aliasGreet());
};
button2.textContent = "With reference";
button2.onclick = function () {
alert(greeter.aliasGreetSecond());
};
document.body.appendChild(button);
document.body.appendChild(button2);