代码之家  ›  专栏  ›  技术社区  ›  eozzy

在显示原型模式的javascript中访问变量

  •  3
  • eozzy  · 技术社区  · 7 年前
    var tool = function (bID, $element) {
        this.bID = bID || 0;
        this.$element = $element || false;
        this.element = $element[0] || false;
    };
    
    tool.prototype = function () {
    
        // if this.bID == 'x' && this.$element ? ...
    
    }();
    

    如何访问原型函数中最初设置的vars?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Isaac    7 年前
    var tool = function (bID) {
        this.bID = bID || 0;
    };
    
    let testTool = new tool(5);
    
    tool.prototype.logging = function () {
        console.log(this.bID)
    };
    
    testTool.logging();
    

    tool.prototype 是工具的所有属性/属性的容器,换句话说,您不能执行下面的操作

    tool.prototype = function () {
    
        // if this.bID == 'x' && this.$element ? ...
    
    }();
    

    在我的例子中,将函数表达式赋给变量 logging ,然后使用创建的对象调用它,否则将调用您的想法 this 是否创建了没有对象的if?

    更新

    var tool = function (bID = 'x') {
        this.bID = bID || 0;
    };
    
    //console.log(tool.prototype.logging());//TypeError: tool.prototype.logging is not a function
    
    
    let somefunc = function(toolParam) { 
      if(toolParam.bID === 'x'){
        tool.prototype.logging = function () {
          return console.log(this.bID)
        };
      }
    }
    
    let testTool = new tool();
    
        somefunc(testTool);
    
    console.log(tool.prototype.logging)
    //ƒ () {
    //        return console.log(this.bID);
    //    }