这是一个小的Javascript代码片段,其中我使用了一个函数来模拟一个对象。我试图反思成员函数(这是函数的真正嵌套函数),但不知何故代码不起作用。
有人可以帮我理解为什么代码不起作用。我试图理解导致此代码不起作用的Javascript的基本原则。
感谢。
var test = function () {
var first = function first () {
alert ("first");
}
var second = function second () {
alert ("second");
}
};
function getOwnFunctions(obj) {
for(var f in obj) {
if(typeof(f) == "function" && obj.hasOwnProperty(f)) {
alert(f);
}
}
}
getOwnFunctions(test);
答案 0 :(得分:1)
var
关键字引入了一个符号,该符号是函数调用的动态范围的本地符号,而不是this
引用的上下文范围。
答案 1 :(得分:1)
这里有几点:
var
定义变量的范围,即说明
first
& second
函数是
仅在test
内可用
功能。要模拟object
,
您想使用this
关键字。for(var f in obj)
:for
循环
在对象上并返回
obj
中的键,因此typeof(f)
将始终返回该类型
f
变量将是一个
string
,您要查看
typeof(obj[f]])
将返回
实际底层证券的类型
属性。getOwnFunctions
使用test
的实例,而不是。{
实际test
函数:
var test = function () {
this.first = function() {
alert ("first");
}
this.second = function() {
alert ("second");
}
};
function getOwnFunctions(obj) {
for(var f in obj) {
if(typeof(obj[f]) == "function" && obj.hasOwnProperty(f)) {
alert(f);
}
}
}
getOwnFunctions(new test);
答案 2 :(得分:1)
因此,如果您希望函数具有“方法”,则可以将该函数视为对象:
var test = function () {};
test.first = function first () {
alert ("first");
}
test.second = function second () {
alert ("second");
}
function getOwnFunctions(obj) {
for(var f in obj) {
if(typeof(f) == "function" && obj.hasOwnProperty(f)) {
alert(f);
}
}
}
getOwnFunctions(test);
这里最棒的是你可以做以下事情:
function x(y){
alert( y );
}
x.test = function(){this('test');}
x.test();
警报测试