Update README.md

master
Matt Huntington 8 years ago committed by GitHub
parent 0c5ef731ff
commit aef317e52b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -283,54 +283,34 @@ console.log('ES6 square:',squareES6(6));
### Binding ### Binding
Here is an example of the arrow function binding this with callbacks, this can get redefined:
```JavaScript ```JavaScript
// Create constructor function, inputs name, has default friend values function Person(name){
function Person ( name , friends = ["Charlie", "Dennis", "Ron", "Sweet Dee", "Frank"]){
this.name = name; this.name = name;
this.friends = friends; this.logName = function(){
setTimeout(function(){
//Add four methods: console.log(this.name);
},500)
// The first, `secret Admirer`, `this.name` is undefined in the forEach function
this.secretAdmirer = function (){
this.friends.forEach(function ( f ){
console.log( this.name + " sends flowers to " + f );
});
}
//The second one is the way we got around the issue of `this` - which was to set the desired `this` to a variable called `that` or `self` or something similar:
this.giveOldSchoolLove = function (){
var self = this;
this.friends.forEach(function ( f ){
console.log( self.name + " likes " + f );
});
} }
// we could also use .bind()
this.giveBindingAffection = function (){
this.friends.forEach(function ( f ){
console.log( this.name + " makes friendship bracelets for " + f )
}.bind(this));
} }
var me = new Person('Matt');
me.logName();
```
//Finally, by using the arrow function, `this` is already bound: arrow functions fix this:
this.giveNewSchoolLove = function (){ ```javascript
this.friends.forEach(f => console.log( this.name + " hearts " + f )); function Person(name){
this.name = name;
this.logName = function(){
setTimeout(()=>{
console.log(this.name);
},500)
} }
} }
var me = new Person('Matt');
//See examples me.logName();
k = new Person ( "Matt" );
console.log( 'Secret Admirer:' );
k.secretAdmirer();
console.log( 'Show old school love:' );
k.giveOldSchoolLove();
console.log( 'Show new school love:' );
k.giveNewSchoolLove();
``` ```
## Support for Classes ## Support for Classes

Loading…
Cancel
Save