[JS] 函数

一、函数的创造方法

声明式

函数会被提到 js 程序的最上方执行,所以在函数声明的前面也可以调用它。

function f(x) {
    return x+1;
}

定义式

必须先定义后使用

var g = function (x) {
    return x + 2;
} 

比如以下程序,f(5) 能正常输出,g(5) 处会报错 Uncaught TypeError: g is not a function

document.writeln(f(5));
document.writeln(g(5));

function f(x) {
    return x+1;
}

var g = function (x) {
    return x + 2;
} 

二、函数的原型

当用上面任意方法创造函数 h 后,h 的原型就为 Function.Prototype,如果往原型里添加方法,就能让通过 new h() 得到的对象共享这个方法。

// 给Function.prototype增加一个方法,所以函数都能用  
Function.prototype.method = function (name, func) {  
  this.prototype[name] = func;  
    return this;  
};  
  
// Number 是一个constructor,它的原型是Function.prototype, 所以可以调用method  
// 给 Number.prototype 增加了名为integer的方法,作用是取整  
Number.method('integer', function () {  
  return Math[this < 0 ? 'ceil' : 'floor'](this);  
});  
  
//(-10/3)会转换成 new Number(-10/3),可以调用integer  
document.writeln((-10 / 3).integer());
posted @ 2019-02-10 15:22  wanyi1996  阅读(159)  评论(0编辑  收藏  举报