首页 > 解决方案 > 在javascript中访问变量揭示原型模式

问题描述

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 ? ...

}();

如何访问最初在原型函数中设置的变量?

标签: javascript

解决方案


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

更新

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);
//    }

推荐阅读