q第4章 函数(Functions)

4.1 函数对象

  • 对象字面量产生的对象连接到object.prototype,函数对象连接到Function.prototype(该原型对象本身也连接到object.prototype)

4.3 调用 Invocation

  • 函数被调用时,接收两个附加的参数:thisarguments
  • 当实际参数(arguments)与形式参数(parameters)的个数不匹配时不会导致运行时错误。
  • 实际参数过多,超出的参数值被忽略
  • 过少,缺失的值被替换为undefined。
  • 对参数值不会进行类型检查:任何类型的值都可以传递
javascript的四种调用模式
  • 方法调用模式 The Method Invocation Pattern
    当一个方法被调用时,this被绑定到该对象
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可取得它们所属对象的上下文的方法称为公共方法。

  • 函数调用模式 The Function Invocation Pattern
    当一个函数不是对象的属性的时候,它被当作函数来调用。此时this绑定到全局对象
    这是个错误的设计,因为方法在调用内部函数时,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
  • 构造器调用模式 The Constructor Invocation Pattern
    Js是一门基于原型继承的语言,但也提供了一套和基于类的语言相似的对象构建方法。
    如果在一个函数前面带上new来调用,那么将创建一个隐藏连接到该函数的prototype成员的新对象,同时this将会绑定到那个新对象上。
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());

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

  • Apply调用模式 The Apply Invocation Pattern
    apply方法接收两个参数,第一个绑定到this,第二个是参数数组。
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

  • return语句可用来使函数提前返回。
  • 一个函数总是会返回一个值,如果没有指定返回值,则返回undefined。
  • 如果函数以在前面加上new前缀的方式来调用,且返回值不是一个对象,则返回this(该新对象)

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

你可能感兴趣的:(q第4章 函数(Functions))