问题
If i want to destruct an Object i would do :
const obj = {
a: 'a',
fn: () => 'some function'
}
// const fn = obj.fn;
// OR
const {
a,
fn
} = obj;
console.log( fn() );
this doesn't work for the Date Object :
Uncaught TypeError: this is not a Date object.
const date = new Date();
const day = date.getDate();
console.log(day); // works
const {
getDate
} = date;
console.log( getDate() ); // doesn't work
Why is this possible with the first Object and not with the Date ? how would one acheive that if it's possible.
回答1:
Because this it not a Date object. When you call getDate() without its proper context (ie. date.getDate()), then you're calling it in the context of the window (or null in strict mode). Neither window nor null are Date objects, therefore the function fails.
Try const getDate = date.getDate.bind(date);
Demo:
const test = { fn : function() { return this.constructor; } };
const normal = test.fn();
console.log(normal); // object
const {fn} = test;
console.log( fn() ); // window
const bound = test.fn.bind(test);
console.log( bound() ); // object
回答2:
It's likely not worth it, but you could write a function to help you destructure methods from an object. Here bindMethods does this, using helper allKeys, which collects the keys from the entire prototype chain of an object and which in turn depends on walkPrototypeChain. They could obviously be folded into a single function if desired.
const walkPrototypeChain = (process, init, finish) => (obj) => {
let currObj = obj, currRes = init();
do {
currRes = process(currRes, currObj)
} while (currObj = Object.getPrototypeOf(currObj))
return finish(currRes)
}
const allKeys = walkPrototypeChain(
(set, obj) => {Object.getOwnPropertyNames(obj).forEach(k => set.add(k)); return set},
() => new Set(),
s => [...s]
)
const bindMethods = (obj) => allKeys(obj).reduce(
(o, n) => typeof obj[n] == 'function' ? ({...o, [n]: obj[n].bind(obj)}) : o,
{}
)
const date = new Date()
const {getDate, getFullYear} = bindMethods(date) // or any other date function
console.log(getDate())
console.log(getFullYear())
来源:https://stackoverflow.com/questions/54447932/destructuring-a-function-from-object-date-object