我需要复制一个对象及其方法.因此,我对该对象进行字符串化,然后解析它并从原始对象添加方法(但绑定到此新副本).
// Taken from: https://stackoverflow.com/questions/31054910/get-functions-methods-of-a-class
function getAllMethods(obj) {
let props = [];
do {
const l = Object.getOwnPropertyNames(obj)
.concat(Object.getOwnPropertySymbols(obj).map(s => s.toString()))
.sort()
.filter((p, i, arr) =>
typeof obj[p] === 'function' && //only the methods
p !== 'constructor' && //not the constructor
(i == 0 || p !== arr[i - 1]) && //not overriding in this prototype
props.indexOf(p) === -1 //not overridden in a child
)
props = props.concat(l)
}
while (
(obj = Object.getPrototypeOf(obj)) && //walk-up the prototype chain
Object.getPrototypeOf(obj) //not the the Object prototype methods (hasOwnProperty, etc...)
)
return props;
}
function copyObject(obj) {
var copy = JSON.parse(JSON.stringify(obj));
// Copy all methods
getAllMethods(obj)
.filter(prop => typeof obj[prop] === 'function')
.forEach(prop => copy[prop] = obj[prop].bind(copy));
return copy;
}
Run Code Online (Sandbox Code Playgroud)
这里有一些测试:
var foo = { bar:2, f: function() { this.bar = 5 } }
var bar = copyObject(foo);
var baz = copyObject(bar);
bar.f();
bar.bar; // 5
baz.f();
baz.bar; // 2 instead of 5..?!
baz.f.apply(baz); // not working either, baz.bar still 2
Run Code Online (Sandbox Code Playgroud)
为什么副本副本不能像我期望的那样工作?
编辑:在baz.f该this引用仍然被绑定到bar出于某种原因.
它不会因为你只能工作.bind()在this一次上一个函数值.这个this值基本上是在您第一次使用时设置的bind(),之后,您只是在已经绑定的函数之上"绘制另一个图层":
function myFunc() {
console.log(this.a);
}
var f1 = myFunc.bind({
a: 5
});
var f2 = f1.bind({
a: 6
});
f1();
f2();Run Code Online (Sandbox Code Playgroud)
另请注意,您根本无法重新绑定this箭头功能:
var a = 2;
var myFunc = () => {
console.log(this.a);
}
var f1 = myFunc.bind({
a: 5
});
var f2 = f1.bind({
a: 6
});
f1();
f2();Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32 次 |
| 最近记录: |