Skip to content

Instantly share code, notes, and snippets.

@AyaMorisawa
Last active June 1, 2017 14:12
Show Gist options
  • Save AyaMorisawa/11976e490105107492f41e377e48fc94 to your computer and use it in GitHub Desktop.
Save AyaMorisawa/11976e490105107492f41e377e48fc94 to your computer and use it in GitHub Desktop.
class Human {
private age: number = 42;
getAge() {
return this.age;
}
}
let f = new Human().getAge
console.log(f());
class Human {
private age: number = 42;
constructor() {
this.getAge = this.getAge.bind(this);
}
getAge() {
return this.age;
}
}
let f = new Human().getAge
console.log(f());
class Human {
private age: number = 42;
getAge() {
return this.age;
}
}
Human.prototype = bind(Human.prototype);
let f = new Human().getAge
console.log(f());
function bind(obj) {
return new Proxy(obj, {
get(target, name, receiver) {
const x = target[name];
return typeof x === 'function' ? x.bind(receiver) : x;
}
});
}
class Human {
private age: number = 42;
@autobind getAge() {
return this.age;
}
}
let f = new Human().getAge
console.log(f());
function autobind(target, key, { value: method, configurable, enumerable }: PropertyDescriptor) {
if (typeof method !== 'function') {
throw new SyntaxError('@autobind can only be used on methods');
}
return {
configurable,
enumerable,
get() {
const boundMethod = method.bind(this);
Object.defineProperty(this, key, {
configurable: true,
writable: true,
enumerable: false,
value: boundMethod
});
return boundMethod;
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment