44608

Javascript Callbacks with Object constructor

Following is a function which creates and object and call the callback (not the exact code but something similar).

myObject = function(callback){ var tmpThis = this; this.accounts = []; tmpThis.accounts[0] = 1; tmpThis.accounts[1] = 2; callback(); } function caller(){ var newMyObject = new myObject(function() { alert(newMyObject.accounts[1]); }); }

newMyObject is undefined inside the callback function. Is there a way I can access it. I read similar questions but none simply explains why.

I can fix it by passing back the created object in a second parameter to the callback function. But I think its a hack rather than the proper way.

Answer1:

You can use this to access the callback in the context of the newly create object, and call to invoke the callback.

myObject = function(callback){ var tmpThis = this; this.accounts = []; tmpThis.accounts[0] = 1; tmpThis.accounts[1] = 2; callback.call(this); } function caller(){ var newMyObject = new myObject(function() { alert(this.accounts[1]); }); }

Answer2:

The call hasn't finished yet. Set it to run in the next cycle:

http://fiddle.jshell.net/gWUD9/

myObject = function(callback){ var tmpThis = this; tmpThis.accounts = []; tmpThis.accounts[0] = 1; tmpThis.accounts[1] = 2; setTimeout(callback,1); } var newMyObject = new myObject(function() { alert(newMyObject.accounts[0]); });

Answer3:

You could try this:

function Application () { var self = this; myObject = function(callback){ var tmpThis = this; this.accounts = []; tmpThis.accounts[0] = 1; tmpThis.accounts[1] = 2; callback(); }; function caller(){ self.newMyObject = new myObject(function() { alert(self.newMyObject.accounts[1]); }); } }

Answer4:

newMyObject is not aware of newMyObject inside of the parameter which is passed into it. It will be undefined.

In other words, when alert(newMyObject.accounts[1]); is run, newMyObject as defined by new myObject wont exist yet.

newMyObject will be undefined when it is executed by the statement callback();, which runs the following code:

function() { alert(newMyObject.accounts[1]); }

Your callback function is being passed into your myObject function. You can just alert(accounts[1]) from within your myObject function.

The pattern you are attempting to use does not usually take a function callback. Usually you would pass in a object of options, which would serve to customize myObject.

It is not clear what you are trying to do.

Recommend

  • How to design a distributed application using a Message Broker and a Database?
  • Python timer script doesn't run when set to long periods later
  • Retrieve Windows Update history using WUAPILib from a remote machine
  • R mlogit on my data giving error 'system is computationally singular?
  • Subclassing a Pandas DataFrame, updates?
  • Modifying files nested in tar archive
  • https in htaccess and order of rules (using Expression Engine)
  • Submission of new app with iAds
  • C++ Pointer Arrays
  • Angular2 - Template reference inside NgSwitch
  • Yii2: Finding file and getting path in a directory tree
  • Getting error 'Cannot read property 'document' of undefined' while importing exp
  • JPA flush vs commit
  • Elasticsearch script query involving root and nested values
  • Updating both a ConcurrentHashMap and an AtomicInteger safely
  • Why use database factory in asp.net mvc?
  • How do I configure context broker accept post requests from my remote sensor?
  • Sequential (transactional) API calls in angular 4 with state management
  • WPF ICommand CanExecute(): RaiseCanExecuteChanged() or automatic handling via DispatchTimer?
  • How solve “Qt: Untested Windows version 10.0 detected!”
  • Regex thinks I'm nesting, but I'm not
  • Accessing IRQ description array within a module and displaying action names
  • Bug in WPF DataGrid
  • Finding past revisions of files in StarTeam w/ .NET SDK / C#
  • TFS: Get latest causes slow project reloading
  • Where to put my custom functions in Wordpress?
  • How can I use Kendo UI with Razor?
  • How to make Safari send if-modified-since header?
  • Apache 2.4 - remove | delete | uninstall
  • Matrix multiplication with MKL
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • InvalidAuthenticityToken between subdomains when logging in with Rails app
  • Unit Testing MVC Web Application in Visual Studio and Problem with QTAgent
  • Proper folder structure for lots of source files
  • SQL merge duplicate rows and join values that are different
  • Benchmarking RAM performance - UWP and C#
  • LevelDB C iterator
  • Can't mass-assign protected attributes when import data from csv file
  • Is there any way to bind data to data.frame by some index?
  • How can I use `wmic` in a Windows PE script?