gpt4 book ai didi

JavaScript 反射

转载 作者:行者123 更新时间:2023-12-03 00:04:09 29 4
gpt4 key购买 nike

有没有办法从 JavaScript 对象内部获取所有方法(私有(private)、特权或公共(public))?这是示例对象:

var Test = function() {
// private methods
function testOne() {}
function testTwo() {}
function testThree() {}
// public methods
function getMethods() {
for (i in this) {
alert(i); // shows getMethods, but not private methods
}
}
return { getMethods : getMethods }
}();

// should return ['testOne', 'testTwo', 'testThree', 'getMethods']
Test.getMethods();

当前的问题是getMethods()中的代码,简化的示例将仅返回公共(public)方法,而不返回私有(private)方法。

编辑:我的测试代码可能(或可能不会)使我希望得到的结果过于复杂。鉴于以下情况:

function myFunction() {
var test1 = 1;
var test2 = 2;
var test3 = 3;
}

有没有办法从 myFunction() 中找出 myFunction() 中存在哪些变量。伪代码如下所示:

function myFunction() {
var test1 = 1;
var test2 = 2;
var test3 = 3;

alert(current.properties); // would be nice to get ['test1', 'test2', 'test3']
}

最佳答案

隐藏这些方法的技术原因有两个。

首先,当您在 Test 对象上执行方法时,“this”将是在匿名函数末尾返回的无类型对象,该函数包含 Module Pattern 中的公共(public)方法。 。

其次,方法 testOne、testTwo 和 testThree 不附加到特定对象,并且仅存在于匿名函数的上下文中。您可以将这些方法附加到内部对象,然后通过公共(public)方法公开它们,但它不会像原始模式那么干净,并且如果您从第三方获取此代码,它也无济于事。

结果看起来像这样:

var Test = function() {
var private = {
testOne : function () {},
testTwo : function () {},
testThree : function () {}
};

function getMethods() {
for (i in this) {
alert(i); // shows getMethods, but not private methods
}
for (i in private) {
alert(i); // private methods
}
}
return { getMethods : getMethods }
}();

// will return ['getMethods', 'testOne', 'testTwo', 'testThree']
Test.getMethods();

编辑:

不幸的是,没有。局部变量集无法通过单个自动关键字访问。

如果您删除“var”关键字,它们将附加到全局上下文(通常是窗口对象),但这是我所知道的唯一与您所描述的行为类似的行为。不过,如果您这样做,该对象上将会有很多其他属性和方法。

关于JavaScript 反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/275351/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com