Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript原型模式中访问变量_Javascript - Fatal编程技术网

在javascript原型模式中访问变量

在javascript原型模式中访问变量,javascript,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 ? .

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

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

}();
tool.prototype
是工具所有属性/属性的容器,换句话说,您无法执行下面的操作

var tool = function (bID) {
    this.bID = bID || 0;
};

let testTool = new tool(5);

tool.prototype.logging = function () {
    console.log(this.bID)
};

testTool.logging();
而是将函数表达式赋给一个变量,在我的例子中是
logging
,然后使用您创建的对象调用它,否则如果没有创建对象,您认为
this
是什么

更新

tool.prototype = function () {

    // if this.bID == 'x' && this.$element ? ...

}();

稍后我将创建该对象,但我需要在prorotype函数中包含一些条件代码,这需要访问该工具的属性。例如,我想检查元素是否存在,否则不公开任何元素functions@3zzy:请看一下我的更新,看看我是否清楚地理解您所指的内容?
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);
//    }