Javascript 是否可以在函数中重新定义函数中的参数?
我只能在Javascript 是否可以在函数中重新定义函数中的参数?,javascript,Javascript,我只能在功能a中更改代码。例如,如果我有: Object.define(窗口,'App',{get:console.log.bind(null,'World')}) 微信会将我的代码转换成: const App = console.log.bind(null, 'Hello') Object.defineProperty(window, 'App', { set: ()=> { console.error("You are not allow to modify App");
功能a
中更改代码。例如,如果我有:
Object.define(窗口,'App',{get:console.log.bind(null,'World')})代码>
微信会将我的代码转换成:
const App = console.log.bind(null, 'Hello')
Object.defineProperty(window, 'App', {
set: ()=> {
console.error("You are not allow to modify App");
}
})
const sandbox = (App, Function, window) => {
'use strict';
function a() {
'use strict';
// *** I can only modify codes within this block ***
Object.define(window, 'App', {get: console.log.bind(null, 'World') });
// *** I can only modify codes within this block ***
}
function b() {
'use strict';
App();
}
a();
b();
};
sandbox(App, ()=>(()=>({})), undefined);
现在,我想在函数a
中修改应用程序,这样我就可以在函数b
中更改它的行为,这样它就可以打印世界
,而不是你好
你对这个答案的评论是:
让我澄清一下。我只能在函数(func)
中更改代码。其余代码由微信生成
在该函数中,您无法将其声明的函数的App
和Page
参数转换为getter
看起来您正试图用一个getter替换一个参数,也许这样您就可以在代码读取它时观察它了。不,您不能这样做,因为参数不是对象的属性。ª
当然,您可以使用getter定义一个对象,并在函数体中使用该对象,而不是直接使用参数:
function(App, Page) {
const params = {
get App() {
// ...observe the read...
return App;
},
get Page() {
// ...observe the read...
return Page;
}
};
// Use `params.App` and `params.Page` in the body of the function.
}
…但这相当复杂
(Ugh.我刚刚意识到,在松散模式下,如果使用和(params){/*…*/}
包装函数体,App
和Page
将解析对象属性并触发getter。[必须是松散模式,因为严格模式不允许使用]请不要这样做,也许只是作为一种简单的调试策略。:-)
1(至少,您的代码无法访问其中一个。它们是词法环境对象中概念上的绑定,但1.绑定不是属性[尽管它们相似];2.这是概念上的,实际的JavaScript引擎可能会对此进行优化;3.JavaScript代码无法访问词法环境对象[最重要的是,它们可以被优化掉]。:-)App='newAppVal'
?您可以使用Object.defineProperty
来定义对象上的getter/etc,例如如果App
是一个对象,并且您想更改App.foo
被访问时发生的情况有没有简单赋值不起作用的原因?“是否可以重新定义getter”-App
是一个普通变量,由参数声明引入。没有getter。@当然性能App和Page的设置器已被修改。让我澄清一下。我只能更改函数(func)中的代码。其余代码由微信生成。我也可以完全控制此功能范围,但我必须更改全局行为,以便其他开发人员可以使用我修改的应用程序和页面,在其所有Javascript文件中导入代码。@AeroWang-如果您只能将代码放入该功能中,则不能打开App
和页面
将其父函数添加到getter中。我已将其添加到答案的顶部。这就是我的想法。根本无法满足此要求。