q第4章 函数(Functions)

2016-06-06  本文已影响47人  没人能救你呀吼

4.1 函数对象


4.3 调用 Invocation

javascript的四种调用模式
var myObject = {
    value:0,
    increment: function(inc){
        this.value += typeof inc === 'number'?inc:1;
    }
};
myObject.increment();
document.writeln(myObject.value);  //1
myObject.increment(2);
document.writeln(myObject.value);  //3

this到对象的绑定发生在调用的时候。
通过this可取得它们所属对象的上下文的方法称为公共方法

myObject.double = function(){
    var that = this ;//解决方法

    var helper = function(){
        that.value = add(that.value,that.value);
    }
    helper();//函数调用模式
}
myObject.double();
document.writeln(myObject.value);//6
var Quo = function (string){
    this.status = string;
};
Quo.prototype.get_status = function (){
    return this.status;
};
var myQuo = new Quo("confused");
document.writeln(myQuo.get_status());

约定构造器函数要大写!
顺便不推荐这种方式,下一章有更好的替代方法。

var array = [3,4];
var sum = add.apply(null,array);
document.writeln(sum);
var statusObject = {
    status : 'A-OK'
};
//虽然statusObject不继承于 Quo.prototype,但依然可以调用get_status方法
var status = Quo.prototype.get_status.apply(statusObject);
document.write(status);

4.5 返回 Return


4.6 异常 Exceptions

JS提供了一套异常处理机制,throw语句中断函数的执行。它应该抛出一个exception对象,该对象包含可识别异常类型的name属性和一个描述性的message属性。也可以添加其他属性。
该exception对象将被传递到一个try语句的catch从句

var add2 = function(a,b){
    if(typeof a !== 'number' || typeof b !== 'number'){
        throw {
            name: 'TypeError',
            message: 'add needs numbers'
        };
    }
    return a+b;
}
var try_it = function(){
    try {
        add2('seven');
    }catch(e){
        document.writeln(e.name+':'+e.message);
    }
}
try_it();

4.7 给类型增加方法 Augmenting Types

为什么这里是给Function增加方法而不是Object?Number是在Function的原型链上的吗?
JS允许给语言的基本类型增加方法。

//定义新方法,这样就不用总是输入prototype了
Function.prototype.method = function(name, func) {
    if(!this.prototype[name]) {
        this.prototype[name] = func;
        return this;
    }
}

Number.method('integer', function() {
    return Math[this < 0 ? 'ceil' : 'floor'](this);
})

4.10 闭包 Closure

上一篇 下一篇

猜你喜欢

热点阅读