学习笔记一

70 阅读3分钟

1.void运算符

void常见出现场景,在代码中返回undefined

let val=void 0;
console.log(val)
// 输出:undefined

let val2=void 'a';
console.log(val)
// 输出:undefined

let val3=void {};
console.log(val3)
// 输出:undefined

可以看出void运算符后面跟什么都会立即执行并返回undefiend;所以可以利用这个特性永远得到undefined的值

void另外一个特性,他后面的跟着的声明函数是局部函数,不会被提升到全局:

// test_void.js
void function a_test(){
  console.log('函数a_test')
}

function a_test2(){
  console.log('函数a_test2')
}

console.log('是否有a_test函数',window.a_test)
//输出为: 是否有a_test函数 undefined
console.log('是否有a_test函数',window.a_test2)
// 输出为:是否有a_test函数 ƒ a_test2(){
//  console.log('函数a_test2')
//}

void同时也可以立即执行函数:

function a(){
  console.log('a函数')
}
void a();
// 输出为:a函数

void function(){
  console.log('匿名函数')
}()
// 输出为:匿名函数

2.全局属性undefinend在chrome中的表现

var undefined='a'
console.log(undefined)
// 输出为:undefined

以前undefined是可能在全局属性中被意外修改的,现在在新版本chrome浏览器中是无法被篡改的永远返回undefined

但是在局部变量中undefined变量是可以被篡改的,所以要避免在局部变量中修改undefined;

console.log(undefined)
// 输出为: undefined
function test(){
  let undefined='hi';
  console.log(undefined)
}
test();
//输出为: hi

console.log(undefined)
// 输出为: undefined

3.new运算符

用于构建函数调用,通过new.target判断当前函数是否使用了new运算符执行了构建函数:

function Person(name,age){
  if(new.target){
    this.name=name;
    this.age=age;
  }
  else{
    return {
      name:name,
      age:age
    }
  }
}

let person=new Person('jack',22);
console.log(person)
// 输出为:Person {name: 'jack', age: 22}

console.log(Person('jack',22))
// 输出为:{name: 'jack', age: 22}

new运算符在常见内置对象中的表现:
被调用时和被构造时表现一致的内置对象有Array、Error、Function、Date

console.log(Array(2))
// 输出为:[空属性 × 2]
console.log(new Array(2))
// 输出为:[空属性 × 2]

let funcStr=`

let a='Function'
console.log('变量a',a)
`;
console.log(Function(funcStr)())
// 输出为:变量a Function
console.log(new Function(funcStr)())
// 输出为:变量a Function


console.log(Error('异常'))
//输出为: Error: 异常
console.log(new Error('异常'))
//输出为:Error: 异常

console.log(Date())
// 输出为:Mon May 05 2025 13:17:26 GMT+0800 (中国标准时间)
console.log(new Date())
// 输出为:Mon May 05 2025 13:17:26 GMT+0800 (中国标准时间)

在被调用时将它们的参数强制转换为相应的原始类型,而在被构造时返回包装对象,这样的内置对象有Boolean、Number、String

console.log(Boolean(0))
// 输出为:false
console.log(new Boolean(0))
// 输出为:Boolean {false}
console.log((new Boolean(0)).valueOf()===false)
// 输出为:true


console.log(Number(123))
// 输出为:123
console.log(new Number(123))
// 输出为:Number {123}
console.log((new Number(123)).valueOf()===123)
// 输出为:true

console.log(String('abc'))
// 输出为:abc
console.log(new String('abc'))
// 输出为:String {'abc'}
console.log((new String('abc')).valueOf()==='abc')
// 输出为:true

注意其中valueOf方法把对象转为基本类型值。

不使用new运算符会报错的内置对象有Proxy、Map
不能使用new运算符的内置对象有Symbol、BigInt