克隆原型功能保持范围

Clone prototype function keeping scope

本文关键字:范围 功能 原型      更新时间:2023-09-26

我有一个有点奇怪的用例,但在这里(下面是一个例子,但方法的命名有些不同);

在我使用的对象上有一个原型函数名称bootstrap,它调用函数create。我想修改它(不改变原型),以便调用createCustom。要做到这一点,我正在toString()原型函数,在create -> createCustom上做字符串替换,然后eval将其返回到函数。

问题是bootstrap函数在它内部有几个对this的引用,并且似乎我的克隆函数不再具有相同的作用域(预期的那种)。

任何想法,如果我可以绑定一个特定的上下文,让它回到它应该是在克隆方法?不幸的是,到目前为止,我所尝试的一切都没有奏效。

我意识到得到我上面想要的东西的方法是混乱的,但是我无能为力。提前感谢!

一旦你有了你的eval 'd函数,你可以通过Function#callFunction#apply使用任何this值来调用它:

// Call f with `this` referring to `obj`, arguments 1, 2, and 3
f.call(obj, 1, 2, 3);
// Same thing, note how the arguments are passed as an array
f.apply(obj, [1, 2, 3]);

生活例子:

function Foo(name) {
  this.name = name;
}
Foo.prototype.bootstrap = function() {
  create(this.name);
};
var obj = new Foo("The object");
// Not that I recommend doing this!
var f = eval("(" + obj.bootstrap.toString().replace(/'bcreate'b/g, "createCustom") + ")");
snippet.log("b");
snippet.log("Executing: obj.bootstrap()");
obj.bootstrap();
snippet.log("Executing: f.call(obj)");
f.call(obj);
function create(n) {
  snippet.log("create called with '" + n + "'");
}
function createCustom(n) {
  snippet.log("createCustom called with '" + n + "'");
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>