JS

232 阅读2分钟

JavaScript进阶-慕课手敲实例教程

Equality: == (loose-equals), === (strict-equals), != (loose not-equals), !== (strict not-equals), as in a == b.

See "Values & Types" and Chapter 2.

Converting Between Types

So if you use the == loose equals operator to make the comparison "99.99" == 99.99, JavaScript will convert the left-hand side "99.99" to its number equivalent 99.99. The comparison then becomes 99.99 == 99.99, which is of course true.

JavaScript uses the latter approach, dynamic typing, meaning variables can hold values of any type without any type enforcement.

var amount = 99.99;

amount = amount * 2;

console.log( amount );		// 199.98

// convert `amount` to a string, and
// add "$" on the beginning
amount = "$" + String( amount );

console.log( amount );		// "$199.98"

string number boolean null undefined objects

"98.23" == 98.23 // true
"98.23" === 98.23 // false

== allow the implicit coercion === not allow implicit coercion

To boil down a whole lot of details to a few simple takeaways, and help you know whether to use == or === in various situations, here are my simple rules:

If either value (aka side) in a comparison could be the true or false value, avoid == and use ===. If either value in a comparison could be one of these specific values (0, "", or [] -- empty array), avoid == and use ===. In all other cases, you're safe to use ==. Not only is it safe, but in many cases it simplifies your code in a way that improves readability.

if you're comparing two non-primitive values, like objects (including function and array) Because those values are actually held by reference, both == and === comparisons will simply check whether the references match, not anything about the underlying values.

JS中的闭包: 当前作用域能够访问外部作用域中的变量,因为函数是JavaScript中唯一拥有自身作用域的结构,

function Counter(start) {
    var count = start;
    return {
        increment: function() {
            count++;
        },
        get: function() {
            return count;
        }
    }
}

var foo = Counter(4);
foo.increment();
foo.get(); // 5 

JS原型 使用prototype原型模型

JS 函数

函数声明与函数表达式

function add (a, b) {
    ...
    return;
}

// function variable
var add = function (a, b) {
    // do sth
}
// IEF(Immediately Executed Function)
(function() {
    //do sth
})();

// first-class function
return function() {
    //do sth
};

声明 define可以在声明前调用, 但是函数表达式不可以

函数声明 函数表达式 函数构造器

ES6

作用域

全局作用域 函数内作用域 eval

for(var ..) 定义是全局的

var let 当前块作用域

const callbacks2 = []
for (let j = 0; j <= 2; j++) {
    callbacks2[j] = function() {
        return j * 2
    }
}
console.table([
    callbacks2[0](),
    callbacks2[1](),
    callbacks2[2](),
])

BOM

全局作用域 window对象是ECMAScript中的Global对象,所有全局作用域声明的对象都会变成window对象的属性和方法 区别: 全局变量不能通过delete操作符删除,而直接在window对象上定义的属性可以

window打开新的窗口

this对象

this 解析器在调用函数时每次都会向函数内部传递进一个隐含的参数this,this指向一个对象,这个对象我们称为函数执行的上下文对象,根据函数调用方式不同,this指向不同对象

this会根据调用情况发生变化-动态

在构造函数中使用this来引用新建的对象

isinstanceof 来判断实例对象是否是某一个类

取消冒泡 event.cancelBubble = true;