蝴蝶书读书笔记

2016年2月23日

p22.对象是通过引用来定义的,它们永远不会被拷贝。只有独立地显式定义对象,它们才是不同的对象。

var a = b = c = {};
a.d = 'a';
b.d = 'b';
console.log(c);  // {d:'b'}
var a = {}, b = {}, c = {};
a.d = 'a';
b.d = 'b';
console.log(c);  //{}

p26.函数也是对象,因此它也可以由属性,而且属性还可以是一个函数。

var hello = function() {
    console.log('hello');
}
hello.ha = function() {
    console.log('ha');
}
hello.ha(); // ha

 p28.函数调用模式。当一个函数(help)并非一个对象(my.double)的属性时,它被当做一个函数来调用。当函数以此模式调用时,this被绑定到全局对象。这是语言设计上的一个错误。正确的做法是当内部函数被调用时,this应该仍然绑定到外部函数的this变量。解决办法是定一个变量(例如常见的that)并给它赋值为this,那么内部函数就尅通过那个变量访问到this。

value = 10;
// 如果使用var定义的话,第三个输出是undefined,第四个是NaN
// var value = 10;  
var my = {
    value:0,
    increment: function (inc) {
        this.value += typeof inc === 'number' ? inc : 1;
    }
};

my.increment();
console.log(my.value);  // 1
my.increment(2);
console.log(my.value); // 3

my.double = function () {
    var helper = function () {
     // var that = this; console.log(
this.value); // 10 //此处和下面的this都是全局变量 return this.value + this.value; }; this.value = helper(); // 此处的this是my }; my.double(); console.log(my.value); // 20

 p30.apply的作用是改变调用函数的对象。可以使一个贫穷的对象拥有一个富裕的对象的方法。比如:

var a = {
    b : 'hah',
    con : function() {
        console.log(this.b);
    }
};
var b = {
    b : 'heh'
};
a.con();
a.con.apply(b);
/*
使用 apply 可以使 b 调用自己没有的但 a 有的方法 con()
*/

 p32.异常

var add = function (a, b) {
    if ( typeof a !== 'number' || typeof b !== 'number') {
        throw {
            functionName: 'add',
            name: 'typeError',
            message: 'arguments must be numbers'
        };
    };
    return a + b;
};

var try_add = function () {
    try {
        add('sever');
    } catch (e) {
        console.log('function ' + e.functionName + '() ' + e.name + ' : ' + e.message);
    };
};

try_add();

 p33.这里有两个坑。

Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
};
// 首先:method方法是在上面作者自定义的,如果没有加入这个定义,是不可以这样使用的
// 其次:原书中的向上取整是 ceiling ,而正确的应该是 ceil 。。。
Number.method('integer', function() {
    return Math[this < 0 ? 'ceil' : 'floor'] (this);
});
console.log((-10 / 3).integer());  // -3
原文地址:https://www.cnblogs.com/lswit/p/5209348.html