如果构造函数在另一个函数中,则新创建的对象调用构造函数undefined
Newly created objects call to constructor undefined if constructor is inside another function
我刚学会面向对象编程,有一件小事我解决不了。这是一个范围问题。
如果我创建一个新对象,那么我如何能够给它访问我的构造函数,如果构造函数是在另一个函数?现在就没有定义了。将函数存储在全局变量中是行不通的。
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中两个棘手的主题。
相关文章:
- 对使用函数构造函数创建的函数的内部引用
- 获取使用函数构造函数创建的函数的名称
- 为什么可以't JavaScript构造函数创建字符串或数字
- 为什么用构造函数创建对象会执行对象's方法
- 使用构造函数创建对象和返回对象有区别吗
- 通过父构造函数创建主干继承视图
- 使用构造函数创建的数字没有其值作为属性,请取消String与构造函数的链接
- Javascript构造函数创建对象与常规对象
- 为什么更改函数的 .prototype 会影响已使用该构造函数创建的对象的“实例”
- 在 JavaScript 中从构造函数创建编号对象
- 为什么使用函数构造函数创建的 Javascript 函数无法访问在其外部定义的其他函数
- 如何访问使用构造函数创建的对象的属性
- 从构造函数创建一个匿名函数对象,并将其存储在另一个对象中
- 为什么对象构造函数中的函数会改变以前由该构造函数创建的所有对象?
- 通过JS中的对象构造函数创建对象,该构造函数位于单独的JS文件中
- 使用构造函数创建的JavaScript对象的getter和setter
- 通过对象匹配Javascript regexp中的空白,通过regexp构造函数创建
- 如何使用javascript构造函数创建HTML元素
- 访问由构造函数创建的对象中的属性
- 从构造函数创建的对象返回带有构造函数名称的对象,但没有冒号