Skip to content

Instantly share code, notes, and snippets.

@photonstorm
Created November 15, 2011 12:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save photonstorm/1366961 to your computer and use it in GitHub Desktop.
Save photonstorm/1366961 to your computer and use it in GitHub Desktop.
JS question
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() ?
@aduros
Copy link

aduros commented Nov 15, 2011

  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' :)

@photonstorm
Copy link
Author

photonstorm commented Nov 15, 2011 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment