Created
June 7, 2018 15:04
-
-
Save jmcmaster/673e5d6c0934d279262ea0896fb8bf9e to your computer and use it in GitHub Desktop.
this - Part 3 - new and window binding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 1 - Implicit binding | |
| // 2 - Explicit binding | |
| // 3 - new binding | |
| // 4 - window binding | |
| // new Binding | |
| // this is bound to the new object being constructed | |
| var Animal = function(color, name, type) { | |
| //this = {}; JS does this automatically for us behind the scenes. | |
| this.color = color; | |
| this.name = name; | |
| this.type = type; | |
| }; | |
| var zebra = new Animal('black and white', 'Zorro', 'Zebra'); | |
| // window Binding | |
| // if none of the previous rules apply, then default to the window object. Unless youre in strict mode and it will return 'not declared'. | |
| var sayAge = function() { | |
| // 'use strict'; | |
| // strict mode prevents the this keyword from binding to the window in this scenario | |
| console.log(this.age); | |
| } | |
| var me = { | |
| age: 25 | |
| }; | |
| sayAge(); | |
| // undefined | |
| window.age = 35; | |
| sayAge(); | |
| // 35 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment