我的 jquery 脚本中有两个原型(prototype):
script1.prototype.initScript = function() {
//first one
this.saveGrid = function () {
alert("here");
}
};
script1.prototype.otherFunction = function () {
//second
//script1.initScript.saveGrid ?
};
我想在 otherFunction
中调用 saveGrid
。我怎样才能做到这一点?
编辑: 那儿呢?
script1.prototype.initScript = function() {
//first one
this.saveGrid = function () {
alert("here");
}
};
script1.prototype.otherFunction = function () {
//second
$('button').on("click", function(){
//call savegrid here
});
};
谢谢。
最佳答案
您可以通过 this
访问该函数,就像您在创建函数 saveGrid
时在示例中所做的那样。
您应该问问自己,在另一个函数中创建一个函数并在其他函数中重用它们是否是一个好主意。如果您在 initScript
之前调用 otherFunction
会发生什么?
function script1() {}
script1.prototype.initScript = function() {
this.saveGrid = function() {
alert("here");
}
};
script1.prototype.otherFunction = function() {
this.saveGrid();
};
var s = new script1();
s.initScript();
s.otherFunction();
对于第二个示例,您必须在创建事件监听器之前存储this
。
function script1() {}
script1.prototype.initScript = function() {
this.saveGrid = function() {
alert("here");
}
};
script1.prototype.otherFunction = function() {
var that = this;
$('button').on("click", function(){
that.saveGrid();
});
};
var s = new script1();
s.initScript();
s.otherFunction();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>click me</button>
关于javascript - 从其他原型(prototype)调用原型(prototype)中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38769479/