TypeScript电子时钟示例

听说MS出了差不多能“替代”JavaScript的东东,那是啥呢,就是TypeScript,完全兼容JavaScript,好奇之下,试了一下,嘿嘿,感觉不错。
更能体现出OO的思想了,与C#又有极大的相同点(只是语法上挺相似),写起来顺手比原来的JavaScript顺手多了。
下面来演示一个简单的小例子,就是Web页面上的时间,相信会JavaScript的人想都不用想就可以直接敲出来了,但是你有试过用TS写吗?
用C#的概念讲解一下TS:
1、首先定义个命名空间 module--NameSpace
2、增加一个Test类,需要用关键字 export
3、实现类
...具体代码如下:
module Time {
    export class Test {
        element: HTMLElement;
        span: HTMLElement;
        timer:number;
        constructor (e:HTMLElement) {  //构造函数
         this.element=e;
         this.element.innerHTML="Now Time is: ";
         this.span=document.createElement('span');
         this.element.appendChild(this.span);
         this.span.innerHTML=new Date().toTimeString();
        }
        start() {
          this.timer=setInterval(()=>this.span.innerHTML=new Date().toTimeString(),500);
        }
        stop(){
            clearTimeout(this.timer);
        }
    }
}

把上面的TS解析成JS看看是什么样的。

var Time;
(function (Time) {
    var Test = (function () {
        function Test(e) {
            this.element = e;
            this.element.innerHTML = "Now Time is: ";
            this.span = document.createElement('span');
            this.element.appendChild(this.span);
            this.span.innerHTML = new Date().toTimeString();
        }
        Test.prototype.start = function () {
            var _this = this;
            this.timer = setInterval(function () {
                return _this.span.innerHTML = new Date().toTimeString();
            }, 500);
        };
        Test.prototype.stop = function () {
            clearTimeout(this.timer);
        };
        return Test;
    })();
    Time.Test = Test;    
})(Time || (Time = {}));

 两者对比一下是不是觉得TS比JS的代码简洁明了?

接下来测试一下我们TS的类有没有用呢?

之前有说过,TS完全兼容JavaScript,直接用JS来测试吧。

var div=document.createElement('div');
document.body.appendChild(div);
var obj=new Time.Test(div);
var button = document.createElement('button');
button.innerHTML = "Start"
button.onclick = function() {
    obj.start();
}
document.body.appendChild(button);
var buttons = document.createElement('button');
buttons.innerHTML = "Stop"
buttons.onclick = function() {
    obj.stop();
}
document.body.appendChild(buttons);

运行效果!你成功了吗?

原文地址:https://www.cnblogs.com/xiaoyu5062/p/2717785.html