如果构造函数在另一个函数中,则新创建的对象调用构造函数undefined

Newly created objects call to constructor undefined if constructor is inside another function

本文关键字:构造函数 创建 对象 undefined 调用 新创建 另一个 函数 如果      更新时间:2023-09-26

我刚学会面向对象编程,有一件小事我解决不了。这是一个范围问题。

如果我创建一个新对象,那么我如何能够给它访问我的构造函数,如果构造函数是在另一个函数?现在就没有定义了。将函数存储在全局变量中是行不通的。

  var example = new something x(parameter);
    example.i();
    var getFunction;
    var onResize = function() {
        getFunction = function something(parameter) {
            this.i= (function parameter() {
                    // Does something
            });
        };
    };
window.addEventListener('resize', onResize);
onResize();

对于面向对象的javascript,模式应该是这样的。

//defining your 'class', class in quotes since everything is just functions, objects, primitives, and the special null values in JS
var Foo = function (options) {
  // code in here will be ran when you call 'new', think of this as the constructor.
  //private function
  var doSomething = function () {
  }
  //public function
  this.doSomethingElse = function () {
  }
};
//actual instantiation of your object, the 'new' keyword runs the function and essentially returns 'this' within the function at the end
var foo = new Foo(
    {
      //options here
    }
)

如果我理解你的话,你想知道如何访问另一个函数中的变量。您的尝试是合理的,但请注意,直到调用 onResize之后的才绑定getFunction。下面是一个更简洁的演示:

var x;
function y() {
    // The value is not bound until y is called.
    x = function(z) {
        console.log(z);
    }
}
y();
x('hello');
一个常见的JavaScript模式是返回一个代表函数API的对象。例如:
function Y() {
    var x = function(z) {
        console.log(z);
    }
    return {
        x: x
    };
}
var y = Y();
y.x('hello');

你一定要读懂JavaScript的基本概念。你的代码和术语都很草率。我推荐《Secrets of the JavaScript Ninja》。它很好地解释了范围和函数,这是JavaScript中两个棘手的主题。