javascript - 从其他原型(prototype)调用原型(prototype)中的函数

标签 javascript jquery

我的 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/

相关文章:

php - 通过单击链接提交表单,而不使用提交按钮

javascript - 如何调用另一个函数的返回内部函数?

javascript - 断言在磁带中抛出 - Node

javascript - 如何点击<li>的自包含<a>?

jquery - 如何根据悬停的元素动态更改 JQuery 可排序助手?

jquery - Bootstrap 3 - 可折叠的右侧面板,如 Google Drive Details/Activity 面板

javascript - cfcontent 调用顺序令人困惑

Javascript - 从 MS Dynamics CRM Online 添加和检索数据

jquery - 使用 jQuery 淡入附加 div

Javascript过滤方法,删除数组中所有匹配值的项目