Created
November 15, 2011 12:26
-
-
Save photonstorm/1366961 to your computer and use it in GitHub Desktop.
JS question
This file contains 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
A = function () { | |
this.title = null; | |
this.config = new A.Config(); | |
this.test = function () { | |
console.log( "What scope difference is there between me and A.init() ?" ); | |
} | |
}; | |
A.prototype = { | |
constructor: A, | |
init: function ( newTitle ) { | |
this.title = newTitle; | |
} | |
}; | |
A.Config = function ( width, height ) { | |
this.width = width; | |
this.height = height; | |
}; | |
A.Config.prototype = { | |
constructor: A.Config, | |
init: function ( width, height ) { | |
this.width = width; | |
this.height = height; | |
console.log( this.width + " x " + this.height ); | |
console.log( this.title ); // displays: undefined | |
console.log( A.title ); // displays: undefined | |
console.log( myTest.title ); // displays: "bob" | |
} | |
}; | |
var myTest = new A(); | |
myTest.init( "bob" ); | |
myTest.config.init( 320, 240 ); | |
// 1) How can a prototyped function inside A.Config get access to a var/function from A ? | |
// 2) What's the difference (scope?) between a prototyped functions: A.init() vs. A.test() ? |
Author
photonstorm
commented
Nov 15, 2011
via email
Thank you for taking the time to email me - appreciated.
I've since been reading up on JavaScript a lot, especially the way in which
the keyword "this" changes scope based on how the object was called.
Fascinating stuff!
Cheers,
Rich
On 15 November 2011 12:57, Bruno Garcia < ***@***.*** > wrote:
1) You need to pass the instance of A along to A.Config's constructor and
reference it in init. It looks like you want A.Config to work like an inner
class in Java, but that's not the case.
2) None. 'this' will refer to the instance of A (usually) in both. The
form you have with init is better in my opinion. You also don't need to set
prototype.constructor, it's implicitly set by 'new' :)
---
Reply to this email directly or view it on GitHub:
https://gist.github.com/1366961
##
http://www.photonstorm.com
We've got some wild things floating about.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment