javascript - Binding different this scope to ES6 => function operator -
after experimenting inheriting contexts => feature es6 gives noticed context can never changed. example:
var othercontext = { a: 2 }; function foo() { this.a = 1; this.bar = () => this.a; } var instance = new foo; instance.bar(); // returns 1 instance.bar.bind(othercontext)(); // returns 1
without => operator , using function keyword:
function foo() { this.a = 1; this.bar = function () { return this.a; } } var instance = new foo; instance.bar(); // returns 1 instance.bar.bind(othercontext)(); // returns 2
therefore, if receive function external call or have function in variable, how can sure if going able bind different or if inherit somewhere?
it sounds dangerous javascript not tell anything, 1 might fall subtle , difficult bug.
it new syntax bind
, doesn't introduce new in way of gotchas.
var othercontext = { a: 2 }; function foo() { this.a = 1; this.bar = function () { return this.a }.bind(this); } var instance = new foo; log(instance.bar()); // returns 1 log(instance.bar.bind(othercontext)()); // returns 1 function log(value) { document.body.appendchild( document.createtextnode(value) ); }
therefore, if receive function external call or have function in variable, how can sure if going able bind different or if inherit somewhere?
because either:
- you'll have written function in first place or
- you'll have written specification how call function people know pass in function makes use of
this
context choose.
Comments
Post a Comment