gpt4 book ai didi

javascript - 在 javascript 环境中执行

转载 作者:行者123 更新时间:2023-11-28 18:49:33 25 4
gpt4 key购买 nike

我希望允许我的用户在应用某个对象作为环境的同时执行一系列功能。例如,我有一些包含数据和操作的对象。

environment = {

member1 = 0

operation1 = ->
member1 += 1
}

我希望允许用户将命令发送到环境中,就像它是全局对象一样,而不用 this 引用它

environment.evaluate("operation1()")

如果我可以在环境之外创建操作,但允许将它们发送到这个假设的“评估”函数中,那就太好了。

是否可以构建这样的东西?它有原生 JavaScript 支持吗?

最佳答案

changing now. just realized what you needed

这调用私有(private)方法对象的成员。

// create a closure which is your environment using the module pattern
var environment = (function() {

// local variables to the environment
var member1 = 0;

// public interface
var methods = {
operation: function(num) {
return member1 += (num || 1);
},
evaluate: function evaluate(name) {
var rest = Array.prototype.slice.call(arguments, 1);
// call your function by name passing in the rest of the arguments
return typeof methods[name] === 'function' && methods[name].apply(this, rest);
}
}

return methods;
})();

console.assert(typeof member1 === 'undefined', 'member1 is out of scope');
console.assert((environment.evaluate("operation", 2) === 2), 'member1 === 2');
console.log(environment.evaluate("operation", 2));
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>

old answer

我刚刚注意到您请求了 CoffeeScript 。这是你可以使用的 javascript。我从未使用过 CoffeeScript ,但更改为咖啡应该不难,而且咖啡无论如何都会编译为 js。

关键是整个环境有一个闭包,并使用eval来修改内部状态。最好使用特定的 getter 和 setter 将 api 限制为您允许的内容,否则最终用户有权修改范围内的任何内容,因此没有什么是私有(private)的。

// create a closure which is your environment using the module pattern
var environment = (function() {

// local variables to the environment
var member1 = 0;

// return the public interface
return {
// this function evals the code in the context of the environment
evaluate: function evaluate(operation) {
// eval a closure so anything you put in there is run and returned to the outer environment
return eval('(function(){ return ' + operation + '})()');
}
}
})();

console.assert( typeof member1 === 'undefined', 'is member1 out of scope' );
console.log( environment.evaluate("++member1") );

<!-- begin snippet: js hide: false -->
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>

var es6environment = (function() {

let member1 = 0;

const methods = {
operation: (num = 1) => member += num,
evaluate: (name, ...rest) => typeof methods[name] === 'function' && methods[name].apply(this, rest);
}

return methods;
})();
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>

关于javascript - 在 javascript 环境中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34699615/

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