本文介绍了如何访问在函数中的 JavaScript 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 JavaScript 中,有没有办法访问一个函数内的函数,而该函数又位于另一个函数内?
Is there any way to access a function which is inside a function, which is inside an other function in JavaScript?
function x(name, age) {
this.name = name;
this.age = age;
this.a = function() {
this.b = function() {
return "b";
};
return "a";
};
}
var xobj = new x('vin', 25);
console.log(xobj.a.b()); //error
推荐答案
你可以做的
function x(name, age){
this.name =name;
this.age = age;
this.a = function(){
this.b = function(){
return "b";
};
return "a";
};
}
var xobj =new x('vin',25);
var xx = new xobj.a();
console.log(xx.b());
你必须声明一个 x.a() 的实例,然后调用 b
you would have to declare an instance of x.a() and then call b
当一个函数用作构造函数时(使用 new 关键字),它的 this 绑定到正在构造的新对象.所以如果你想在函数 a() 中调用它,你必须使用 new 关键字
When a function is used as a constructor (with the new keyword), its this is bound to the new object being constructed. so If you want to call this inside the function a(), you would have to create a constructor using new keyword
这篇关于如何访问在函数中的 JavaScript 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!