js 语言精粹 4、函数

方法调用

var a = {
    name: 'sfp',
    say: function(){
      console.log('123');
    }
  }
  a.say();

函数调用

var a = {
    name: 'sfp',
    say: function(){
      var that = this;

      var helper = function(){
        that.name +=  'sfp';
        console.log(that.name);
      }
      //函数调用
      helper();
    }
  }
  a.say();

异常

var add = function(a){
    throw{
      name: 'TypeError',
      message: 'add needs numbers'
    }
  }

  var try_it = function(){
    try{
      add('1');
    }catch(e){
      console.log('has throw');
    }
  }

  try_it();

扩充类型的功能

Function.prototype.method = function(name, func){
    if(!this.prototype[name]){
      this.prototype[name] = func;
    }

    return this;
  }

  String.method('test', function(){
    console.log('test');
  })

  '123'.test();

模块

String.method('test1', function(){
    var a = '12';
    // 闭包:也就是返回一个函数
    return function(){
      console.log(a);
    }
  }())

  '123'.test1();

你可能感兴趣的:(js 语言精粹 4、函数)