其他分享
首页 > 其他分享> > ES5与ES6的一些语法比较

ES5与ES6的一些语法比较

作者:互联网

目录

ES5中的闭包

<script>
	var btns = document.getElementsByTagName("button");
	for (var i = 0; i < btns.length; i++) {
		(function (i) {
			btns[i].addEventListener('click', function () {
				console.log('第' + i + '个按钮被点击');
			})
		})(i)
	}
</script>

ES6中的写法

<script>
	const btns = document.getElementsByTagName("button");
	for (let i = 0; i < btns.length; i++) {
		btns[i].addEventListener('click', function (){
			console.log('第' + i + '个按钮被点击');
		})
	}
</script>

对象增强写法

ES5:

<script>
	let name = 'tolerate';
	let age = 25;
	let height = 1.78;

	const person = {
		name : name,
		age : age,
		height : height,
		run : function() {
			console.log('在跑');
		}
	}

	console.log(person);
	person.run();
</script>

ES6:

<script>
	let lname = 'tolerate';
	let lage = 25;
	let lheight = 1.78
	const lperson = {
		lname,
		lage,
		lheight,
		eat() {
			console.log('在吃');
		}
	}

	console.log(lperson);
	lperson.eat();
</script>

标签:ES6,ES5,console,log,语法,let,btns
来源: https://www.cnblogs.com/coderElian/p/15126477.html