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();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容