![](/img/trans.png)
[英]Is it possible to put a constructor function inside a constructor function inside another constructor?
[英]Newly created objects call to constructor undefined if constructor is inside another function
我刚学了 OOP,有一件小事我无法解决。 问题是某种范围的问题。
如果我创建一个新对象,那么如果构造函数在另一个函数中,我将如何让它访问我的构造函数? 现在我没有定义。 将函数存储在全局变量中不会完成这项工作。
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();
对于 OOP 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
}
)
如果我理解你,你想知道如何访问另一个函数中的变量。 您的尝试是合理的,但请注意getFunction
直到onResize
被调用后才会绑定。 这是一个更清晰的演示:
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 的基本概念。 你的代码和术语都很草率。 我推荐JavaScript Ninja 的秘密。 它很好地解释了作用域和函数,这是 JavaScript 中的两个棘手主题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.