TypeScript 中的 this 使用注意

最近的一个项目,用了 typescript 来写js脚本,结果错误百出,修复的同时也让我总结了ts 中该怎样使用this。

ts 提供类似C# 和 java的静态类型(强类型), 在全局和命名空间的全局里面 直接声明一个函数 要用到 function 关键字(就是js的function关键字),而在类(class)里面却不能使用function来声明方法。让我们来比较 它与 C# 的不同

    public delegate int handle();
    public class Program
    {
        public static void Main(string[] args)
        {
            var t = new Test();
            var a = new A();
            t.h = a.hander;
            t.count = t.h();
            Console.WriteLine("count is:{0}",t.count); 
            // output:
            // count is:1
        }
    }
    public class Test
    {
        public handle h;
        public int count = 100;
    }
    public class A
    {
        private int count = 0;
        public int hander()
        {
            this.count +=1;
            return this.count;
        }
    }

这个代码在class A里面 放了一个方法,并将这个方法作为一个委托 给了 class program 的 h 字段, 最后在 Main 方法里面运个 h委托, 结果得到了 1 这个结果(A.count + 1 = 0 + 1 = 1)

让我们在TypeScript 里面实现相同的功能:

class A {
    public count: number = 0;
    public hander(): number {
        this.count += 1;
        return this.count;
    }
}


class Test {
    public count: number = 100;
    public h: () => number;
}

class Program {

    static Main(): void {
        let t = new Test();
        let a = new A();
        t.h = a.hander;
        t.count = t.h();
        console.log(`count is :${t.count}`);
        // output
        // count is :101
    }
}

Program.Main();// 为了跟C#一致 , 提供的静态入口

你会发现,这时候结果不再是1,而是101, 造成差异的原因是js的 this 指针 , 在 C# 中 this 总是指向当前的类,而 js中的this可以改变, 当 t.h = a.hander 的时候 t.h 中的this 变成了 Test 类。 而在 typescript中,因为当前定义的是一个类,所以其this 总是指向 类,所以TS 直接使用js中的this.

然而 有办法解决这个问题么? 当然有。 让我们来改变 class A

class A {
    constructor() {
        this.hander = ()=>{
            this.count += 1;
            return this.count;
        }
    }
    public count: number = 0;
    public hander: () => number;
}

这样我们把hander 从类的 方法 变成了 类的变量,更重要的是 我们在 构造函数里面 使用 lamda 表达式 , 使用 lamda表达式 并不会改变this的作用域, 因为当前是一个构造函数,所以里面的this指向的是 当前的类,(查看一下生成的js会更容易理解, 函数里面已经没有了this)

从js的角度, 因为函数中没有了this指针,所以也就不会因为 传递到其他的地方造成不一致的情况

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值