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