- 作用域
- 作用域:查询变量的工具
作用域链:查询变量的路径(由内向外不可逆)
作用域类型
- 块作用域
- 函数作用域
- 全局使用域
// 流程控制,{},if,while,...{let name = 'admin'console.log(name);}// 仅限块内,外部不可见// console.log(name);console.log('----------------------')
const hello = function(){//私有成员const site = 'php.cn'//私有成员,函数内部可以访问console.log(site)}//访问函数hellohello()console.log('----------------------')
// 块,函数之外的都是全局,全局可见const course = 'JavaScript'//块{console.log(course)}console.log('----------------------')
const item = '手机'const scopeChain = function(){//const item = '电脑'return function(){//const item = '相机'return item}}console.log(scopeChain()())//函数中的变量和全局中变量不是同一个变量,如果在函数中找不到变量,会向上查找。//这个就叫作用域链
**class**,只支持简化语法let product = {productName: '华为(MateXs2)',unitPrice: 9999,getInfo: function(){return `${this.productName} : ${this.unitPrice} 元`},}console.log(product.getInfo());const productName = '华为(MateXs2)'const unitPrice = 9999product = {productName: productName,unitPrice: unitPrice,getInfo: function(){return `${this.productName} : ${this.unitPrice} 元`},}console.log(product.getInfo());console.log('----------------------')
product = {//当属性名与变量名相同时,可只写属性名,不写值变量名//可以理解为这里引用了上面的变量。productName,unitPrice,getInfo: function(){return `${this.productName} : ${this.unitPrice} 元`},}console.log(product.getInfo());console.log('----------------------')
product = {productName,unitPrice,//将 冒号和function删除,就完成了简化//可以理解为:这里定义了一个getInfo()函数// getInfo: function(){getInfo() {return `${this.productName} : ${this.unitPrice} 元`},}console.log(product.getInfo());console.log('----------------------')// ! 能不能用箭头函数来简化方法? 不行 NOproduct = {productName,unitPrice,//箭头函数,箭头函数没有函数名,拿不到thisgetInfo : () => {return `${this.productName} : ${this.unitPrice} 元`},}console.log(product.getInfo());console.log('----------------------')
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号