-
-
Notifications
You must be signed in to change notification settings - Fork 34
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
function类型不支持拷贝吗 #18
Comments
现在函数是没拷贝的,直接赋值了,也就是说拷贝完,两个对象里的函数是同一个 函数如何拷贝呢?能想到的办法,可以使用 有了字符串,可以使用 这里需要将上一部的函数字符串中的参数和,函数体解析出来,这个用正则就可以,但考虑到还ES6的参数默认值和rest参数,还不太简单,现在假设我们解析好了,可以想下面这样拷贝一个函数 function a() { console.log('1') };
const a2 = new Function(`console.log('1')`) 一些问题我在chrome下测试会遇到如下的错误,看起来需要设置CSP的设置才可以,关于CSP看这里:https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP 还有一个问题,拷贝的函数会丢失闭包,感觉只能拷贝不依赖闭包的函数,思考如下例子: function a() {
var a1 = 1;
return function b() {
console.log(a1);
}
}
const b1 = a();
const b2 = clone(b1); // 按照上面的思路,拷贝的b2 打印出来的a1是undefined,这其实拷贝的函数是不对的 this的问题,拷贝函数还要保留this的指向 总结关于拷贝函数的一些思考,可能并不完整,我认为拷贝函数似乎并不简单,现在的方案不能满足需求么?因为函数其实也不会修改 |
字符串的可以这样 new Function(`return ${f.toString()}`)();得到新函数,最好再绑定下上下文?.bind(ctx); 闭包的确实,好像不太好弄,函数确实不太会修改,除非非在函数上加了属性,又直接修改属性,感觉可能性也不大
Hot Blood
***@***.***
…------------------ 原始邮件 ------------------
发件人: ***@***.***>;
发送时间: 2023年7月26日(星期三) 上午10:58
收件人: ***@***.***>;
抄送: "Hot ***@***.***>; ***@***.***>;
主题: Re: [jsmini/clone] function类型不支持拷贝吗 (Issue #18)
现在函数是没拷贝的,直接赋值了,也就是说拷贝完,两个对象里的函数是同一个
函数如何拷贝呢?
能想到的办法,可以使用 Function.prototype.toString拿到函数的字符串,示例如下:
有了字符串,可以使用new Function来新建一个新函数,new Function的函数签名如下:
这里需要将上一部的函数字符串中的参数和,函数体解析出来,这个用正则就可以,但考虑到还ES6的参数默认值和rest参数,还不太简单,现在假设我们解析好了,可以想下面这样拷贝一个函数
function a() { console.log('1') }; const a2 = new Function(`console.log('1')`)
一些问题
我在chrome下测试会遇到如下的错误,看起来需要设置CSP的设置才可以,关于CSP看这里:https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
还有一个问题,拷贝的函数会丢失闭包,感觉只能拷贝不依赖闭包的函数,思考如下例子:
function a() { var a1 = 1; return function b() { console.log(a1); } } const b1 = a(); const b2 = clone(b1); // 按照上面的思路,拷贝的b2 打印出来的a1是undefined,这其实拷贝的函数是不对的
总结
关于拷贝函数的一些思考,可能并不完整,我认为拷贝函数似乎并不简单,现在的方案不能满足需求么?因为函数其实也不会修改
—
Reply to this email directly, view it on GitHub, or unsubscribe.
You are receiving this because you authored the thread.Message ID: ***@***.***>
|
问题是什么
问题的具体描述,尽量详细
环境
在线例子
如果有请提供在线例子
其他
其他信息
The text was updated successfully, but these errors were encountered: