var thing: Doable;
thing = {
private message: 'ahoy-hoy!', // error here
do: () => {
alert(this.message);
doThatThing(thing);
如果我也添加了“意想不到的”方法,也会出现同样的错误:
doThatThing({
do: () => {
alert("ahoy hoy");
doSecretly: () => { // compiler error here now
alert("hi there");
});
我查看了JavaScript,发现内联对象定义中的
this
的作用域是全局对象:
var _this = this; // wait, no, why!?
function doThatThing(doableThing) {
doableThing.do();
doThatThing({
message: 'ahoy-hoy!',
do: function () {
alert(_this.message); // uses global
});
我尝试搜索有关TypeScript中接口的内联实现的信息,但找不到任何与此问题相关的内容。
我可以确认“修复”编译后的JS可以正常工作:
function doThatThing(doableThing) {
doableThing.do();
doThatThing({
message: 'ahoy-hoy!',
do: function () {
alert(this.message);
});
这对我来说很有意义,因为(据我所知)这是隐式调用对象构造函数,所以
this
的作用域应该是新的对象实例。
interface Doable {
do() : void;
class DoableThingA implements Doable { // would prefer to avoid this ...
private message: string = 'ahoy-hoy';
do() {
alert(this.message);
class DoableThingB implements Doable { // ... as well as this, since there will be only one instance of each
do() {
document.getElementById("example").innerHTML = 'whatever';
function doThatThing (doableThing: Doable) {
doableThing.do();
var things: Array<Doable>;
things = new Array<Doable>();
things.push(new DoableThingA());
things.push(new DoableThingB());
for (var i = 0; i < things.length; i++) {
doThatThing(things[i]);
}
更新: François Cardinaux提供了一个指向
的链接,该链接建议使用类型断言,但这只会删除编译器错误,实际上会由于不正确的scope
而导致逻辑错误
interface Doable {
do();
function doThatThing (doableThing: Doable) {
doableThing.do();
doThatThing(<Doable>{ // assert that this object is a Doable
private message: 'ahoy-hoy!', // no more compiler error here
do: () => {
alert(this.message);
});
看看编译后的JS,这是不正确的:
var _this = this; // very wrong, and now hidden
function doThatThing(doableThing) {
doableThing.do();
doThatThing({
message: 'ahoy-hoy!',
do: function () {
alert(_this.message); // s/b "this.message", which works in JS (try it)
});