// 箭头函数表达式(lambda表达式)
// lambda表达式()=>{something}或()=>something相当于js中的函数,它的好处是可以自动将函数中的this附加到上下文中。
// 尝试执行以下:
var shape = {
name: "rectangle",
popup:function(){
console.log('This inside popup(): ' + this.name);//这里可以打印
setTimeout(function(){ //会发现打印不出来,都是空值
console.log('This inside setTimeout(): ' + this.name);
console.log("I'm a" + this.name + "!");
},3000);
setTimeout(()=>{
console.log('This inside setTimeout():' + this.name);
console.log("I'm a" + this.name + "!");
},3000);
}
}
shape.popup();
//谈谈ts的变量声明
var a = 10;
function f(){
var a = 10;
return function g(){
var b = a + 1;
return b;
}
}
var g = f();
console.log(g());//每当调用g,g可以直接访问f中的a变量
//变量作用域
function f(shouldInitialize: boolean) {
if (shouldInitialize) {
var x = 10;
}
return x;
}
f(true); // returns '10'
f(false); // returns 'undefined'
变量x是定义在if语句里面,但是我们却可以在语句的外面访问它。
这是因为var声明可以在包含它的函数,模块,
命名空间或全局作用域内部任何位置被访问。
for (var i = 0; i < 10; i++) {
setTimeout(function() { console.log(i); }, 100 * i);//猜猜这段代码会打印什么?
}
//立即执行函数(IIFE)
for(var i = 0; i < 10;i++){
(function(i){
setTimeout(function(){
console.log(i);
}.100 * i);
})(i);
}
=============================================================
let 声明
let hello = "Hello!";
//块作用域
function f(input : boolean){
let a = 100;
function f(input: boolean){
let a = 100;
if(input){
let b = a + 1;
return b;
}
}
return b;
}
function foo() {
// okay to capture 'a'
return a;
}
// 不能在'a'被声明前调用'foo'
// 运行时应该抛出错误
foo();
let a;
====================================================================
function theCityThatAlwaysSleeps(){
let getCity;
if(true){
let city = "Seattle";
getCity = function() {
return city;
}
}
return getCity();
}
for (let i = 0; i < 10; i++) {
setTimeout(function() { console.log(i); }, 100 * i);
}
const 声明,引用的值是不可变的
解构
解构数组
let input = [1,2];
let [first,second] = input;
console.log(first);
[first,second] = [second,first];
作用于函数参数:
function f([first,second]:[number,number]){
console.log(first);
console.log(second);
}
f(input);
对象解构
let o = {
a:"foo",
b:12,
c:"bar"
};
let {a,b} = o;
console.log(a);
let {a: newName1, b:newName2} = o;
等价于
o.a = newName1;
o.b = newName2;