系列文章目录
提示:阅读本章之前,请先阅读目录
前言
Null
// 1. Null类型的值只有一个,它就是null
const student = null
// 2. null 就是一个空的对象
console.log(typeof student) // object
Undefined
// 1. 没有给变量赋值,那么,值就是undefined
var b; // undefined
// 2. 类型,也是undefined
console.log(typeof b) // undefined
toString
// 1. 不会影响原变量,会返回新的字符串
const name = 123
const nameStr = name.toString()
// 2. 无法对null和undefined转换
const testNull = null;
const testUndefined;
console.log("我会报错,因为我根本就没有toString的方法", testNull.toString())
console.log("我会报错,因为我根本就没有toString的方法", testUndefined.toString())
// 3. 可以使用String()函数转换null和undefined
console.log("用我可以", String(testNull))
console.log("用我可以", String(testUndefined))
Number
// 1. 如果包含字符串,则返回NaN
const num1 = Number("123px")
// 2. 如果是空字符串,则返回0
const num2 = Number(" ")
// 3. 如果是null,则返回0
const num2 = Number(null)
// 4. 如果是undefined,则返回NaN
const num2 = Number(undefined)
// 5. 如果是true,则返回1
const num2 = Number(true)
// 6. 如果是false,则返回0
const num2 = Number(false)
立即执行函数
// 1. 匿名函数
function() {
console.log("我被调用了")
}
// 2. 立即执行
(function() {
console.log("我被调用了")
})();
// 3. 传参
(function(a,b,c) {
console.log("我被调用了")
})(1,2,3);
工厂函数
function createObject(name, age) {
const obj = new Object();
obj.name = name
obj.age = age
return obj;
}
const a = createObject("a", 18)
const b = createObject("b", 26)
垃圾回收GC
call 和 apply
// 1. 可以更变函数的this指向
function hello(a, b) {
console.log("this指向", this)
}
hello() // this指向是window
const obj1 = {}
hello.call(obj1) // this指向是obj1
hello.apply(obj1) // this指向是obj1
// 2. call 第二个参数,第三个参数 。。。 作为实参
hello.call(obj1,1,2)
// 3. apply 第二个参数,必须是个数组
hello.apply(obj1, [1,2])