Typescript-3.箭头函数表达式,变量定义,作用域

// 箭头函数表达式(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;


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值