美文网首页
js 语言精粹 4、函数

js 语言精粹 4、函数

作者: wjing | 来源:发表于2016-05-30 12:43 被阅读17次

    方法调用

    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、函数

          本文链接:https://www.haomeiwen.com/subject/yfhqdttx.html