《Javascript语言精粹》修订版--读书笔记

第二章、语法

语句

下面列出的值被当做false,其他为true:

  • false(boolean)
  • 0和NaN(number)
  • 空字符串(string)
  • null(null)
  • undefined(undefined)

表达式

运算符优先级

运算符 作用
. [] () 提取属性与调用函数
delete new typeof + - ! 一元运算符
* / % 乘除取余
+ - 加法/连接、 减法
>= <= > < 不等式运算
=== !== 等式运算
&& 逻辑与
ll 逻辑或
?: 三元运算

第四章、函数

调用

参数this的值取决于调用模式:
方法调用模式
当一个函数被保存为对象的一个属性时,我们称它为一个方法。方法被调用时,this被绑定到该对象。通过this可取得所属对象的公有方法

var myObject = {
    value:0,
    increment:function(inc){
        this.value += typeof inc === 'number' ? inc : 1;
        console.log(this);  //{value:1,increment:function(){}}
    }
}

函数调用模式
当一个函数并非一个对象的属性时,那么它就是被当做一个函数来调用的,以此模式调用函数时,this被绑定到全局对象。

var myObject = {
    value : 0,
    increment : function(inc){
        this.value += typeof inc === 'number' ? inc : 1;
        console.log(this);  //{value:1,increment:function(){}}
    },
    double : function(){
        var helper = function(){
            console.log(this); //window
        };
        helper();
    }
}

构造器调用模式
如果一个函数前面带上new来调用,那么背地里将会创建一个连接到该函数的prototype成员的新对象,同时this会被绑定到那个新对象上。

function Quo(string){
    this.status = string;
}
Quo.prototype.getStatus = function(){
    return this;
}
var myQuo = new Quo("confused");
console.log(myQuo.getStatus()); //Quo {status: "confused"}

Apply调用模式
apply方法允许我们构建一个函数数组传递给调用函数,也允许选择this的值

var statusObject = {
    status: "ok"
};
function Quo(string){
    this.status = string;
}
Quo.prototype.getStatus = function(){
    return console.log(this); //{status: "ok"}
}
Quo.prototype.getStatus.apply(statusObject);

第七章 正则表达式

第八章 方法

Array

array.sort()
如果这两个参数相等则返回0,如果第1个参数应该排在前面,则返回一个负数,如果第2个参数应该排在前面,则返回一个正数。