JS/使用在函数外部定义的对象

JS/ use object which define outside the function

本文关键字:外部 定义 对象 函数 JS      更新时间:2023-09-26

我在JS中有下一个函数:

function status(){
  this.functionA = function(){}
  //Some others function and fields
}

我还有另一个功能:

function create(root){
var server = libary(function (port) {
  //Here some functions
});
var returnValue = {
  current:status(),
  cur:function(port){
    current.functionA();
  }}
return returnValue;
}

当我调用current.functionA()时,它说电流是未定义的。如何拨打functionA()

当你有一个像 status() 这样的函数构造函数时,你需要为它调用new。我在这里修改了您的部分代码。

var returnValue = {
  current: new status(),
  cur:function(port){
    current.functionA();
  }}
return returnValue;
}

只是为了区分; create()不需要 new 语句,因为您实际上是在函数内部创建和返回要引用的对象。

function status(){
  this.functionA = function(){alert("functionA");}
}
function create(root){ 
    var returnValue = {
        current:status.call(returnValue), 
        cur:function(port){ this.functionA(); }.bind(returnValue)
    } 
    return returnValue; 
}
create().cur(999);

我使用JavaScript"调用"和"绑定"方法纠正了您的问题,这些方法是函数原型的一部分。