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) {
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);
// }
推荐阅读
- vb.net - 具有 2 个以上线程的 Visual Basic 线程
- oracle - 如何在 APEX oracle 中使用动态操作创建视图?
- neural-network - 如何根据示例数量确定深度 NN 训练的架构?
- gridview - 如何将第一条记录添加到 Telerik Radgrid
- r - 正则表达式提取子域
- python-3.x - Seaborn箱线图四分位数计算
- powerbi - 带有 Azure Data Lake Store 的 Power BI Desktop?
- elixir - Elixir - Phoenix - Ecto 术语
- google-cloud-dataflow - Apache Beam TextIO.read 然后合并成批处理
- ruby-on-rails - 在 Rails 5 中选择特定属性