1.Types 类型 & Coercion 类型转换
Primitive Types 原始类型
- underfined
- string
- number
- boolean
- object
- symbol
- null
其中 null
,虽然是基本变量,但是因为设计的时候null
是全 0,而object
是 000 开头,所以 typeof 会误判。
- function - subtype of the object
- array - subtype of the object
这里说的是原始类型,和基本类型、引用类型无关。 基本类型按值访问,存在栈内存 引用类型在栈内存中保存的实际上是对象在堆内存中的引用地址
In Javascript variables don't have types, values do
NaN 是一个特殊的值,某种程度上表明我们进行了某种无效的数值运算
Converting Types
new 关键字
Use new:
- Object()
- Array()
- Function()
- Date()
- RegExp()
- Error()
Don't use new:
- String()
- Number()
- Boolean()
String() 属于字面量表示,指向的是 值引用。 默认会先 new 创建对象,然后调用对象方法,最后删除对象。
var yiifaa = 'yiifaa',
str1 = new String(yiifaa),
str2 = String(yiifaa)
console.log(str1 === yiifaa) //false
console.log(str2 === yiifaa) //true
console.log(typeof str1 === typeof str2) // false
Checking Equality
Falsy
- ""
- 0 , -0
- null
- NaN
- false
- underfined
Truthy
- "foo"
- 123
- true
- function(){ ... }
==
allows coercion
===
disallows coercion
var student1 = "Frank";
var student2 = `${student1}`
var workshop1 = 16;
var workshop2 = workshop1 + 0;
console.log(student1 == student2) // true
console.log(student1 === student2) // true
console.log(workshop1 == workshop2) // true
console.log(workshop1 === workshop2) // true
2.Scope 作用域 / Colsures 闭包
var teacher = "Klyer"
function otherClass() {
teacher = "Suzy"
eco = "React"
console.log("Hello", teacher)
}
otherClass()
console.log(teacher)
console.log(eco)
for (var index = 0; index < 5; index++) {
setTimeout(() => {
console.log(i);
})
}
3.this & Prototypes
this
this 是指调用方法的对象 当 this-aware function 被多个对象调用,this 指向多个作用域(dynamic context),更灵活
// this-aware function
let workshop = {
teacher: "Kyle",
ask(question){
console.log(this.teacher, question)
}
}
// workshop调用ask,所以 ask方法中的this 指向workshop。
workshop.ask("workshop") // Kyle,workshop
function ask(question){
console.log(this.teacher, question)
}
function otherClass(){
var myContext = {
teacher: 'Suzy'
}
// call 修改了 this的指向,this 指向了 myContext 对象
ask.call(myContext, 'Why') // Suzy, Why
}
otherClass()
Prototype
Prototype means that it is an object where any instances are going to be linked to or delegate to. Prototype 是一个对象,任何实例都将链接或委托到该对象 new is gonna invoke that workshop function And the object that gets created is going to be linked to Workshop.prototype. new 关键字 调用 workshop function,并且 创建一个对象,指向 Workshop.prototype。