2011-03-06 40 views
2

这里是一个小小的Javascript代码片段,我使用了一个函数来模拟一个对象。我试图反思成员函数(这是函数的真正嵌套函数),但代码不起作用。反映在一个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); 

回答

1

一对夫妇在这里点:

  1. var定义变量,这是说, first & second功能 只有test 函数内部可用的范围。要模拟object, ,您需要使用this关键字。
  2. for(var f in obj):在for循环 过对象,并返回 obj,所以typeof(f)总是返回,这将是一个 stringf变量的类型,你要检查 typeof(obj[f]])这将返回 属性的实际底层 的类型。
  3. 要拨打getOwnFunctionstest,而不是实际的 功能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); 
+0

@“The Scrum Master”使用“新测试”对我无效。 – Parag 2011-03-06 05:06:02

+0

@parag在萤火虫中为我工作,你使用什么浏览器?尝试'new test()' – 2011-03-06 05:07:51

+0

@“The Scrum Master”我在Chrome上使用此代码片段(Linux上的5.0.375.99测试版)和Firefox 3.5.9上尝试它http://jsfiddle.net/adaptives/QZWgV/ – Parag 2011-03-06 06:15:45

1

var关键字引入一个符号,是本地的函数调用,而不是this所指的上下文范围的动态范围。

+0

我试图从嵌套函数中删除'var'关键字,但也没有成功。 – Parag 2011-03-06 05:07:32

+0

取而代之的是,使用'this.foo =“bar”'定义上下文对象的属性。 – Pointy 2011-03-06 14:02:51

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(); 

通知测试

相关问题