下面的简单示例和JSFiddle在这里 - https://jsfiddle.net/jasondavis/dnLzytju/您可以看到我遇到的问题。从嵌套对象函数调用JavaScript函数失败
我可以看到它为什么会发生,但我不知道如何解决它,同时保持相同的JS结构。
问题是,当我定义一个JavaScript对象原型函数,并且我有一个二级嵌套对象,它具有一个函数,并且在该函数中,我调用父级/根级别上失败的函数。
这从下面this.nestedObject.nested_object_function()
函数的代码试图调用该函数this.normal_function()
但它失败,并说:
Uncaught TypeError: this.normal_function is not a function
at Object.nested_object_function (VM2493:79)
我认为原因是this
被引用this.nestedObject
,而不是父对象。
如果是这样的话,那么我该如何调用该函数,就像我试图从嵌套对象函数中执行并调用父函数一样?
我也试过呼吁JsLibTest.normal_function()
作为this.nestedObject.nested_object_function()
函数的测试,但我得到了同样的错误。
var JsLibTest = (function (document) {
"use strict";
var JsLibTest = function(){
// run init() function on initiation of a new JsLibTest object
this.init();
};
/**
* JsLibTest prototype functions
*/
JsLibTest.prototype = {
init: function() {
// as expected this function runs fine
this.normal_function();
// nested level objects functions run fune from parent level object function
this.nestedObject.nested_object_function();
},
normal_function: function() {
console.log('this.normal_function() ran');
},
nestedObject: {
\t \t // calling a function on the parent object fails here when called from this nested object function
nested_object_function: function() {
\t this.normal_function();
console.log('this.nestedObject.nested_object_function() ran');
},
}
};
return JsLibTest;
})(document);
// run it
$(document).ready(function(){
var Sidebar2 = new JsLibTest();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
感谢多个演示,最后的解决方案似乎是我自己的最佳解决方案。此外,我现在有很多大JS应用程序正在使用这个相同的JS设计,所以你的答案将解决我有很多问题!谢谢! – JasonDavis
@JasonDavis太棒了!我很高兴能够帮到你:) –