Categories
discuss

Why would the ES6 class syntax console log differently than an ES5 class syntax?

I am trying to learn ECMAScript 6 more and inheritance a bit better.

Question: When I console log out bob vs daisy they differ. bob logs a prototype under __proto__ and shows his constructor of run:true;. On the ES6 implementation daisy has no __proto__ however, it still has isRunning accessible. Why?

Enter image description here

var Man = (function(){
  "use strict";
  function Man() {
    this.run = true
  }

  Man.prototype.isRunning = function() {
    console.log('yesss imma run');
  };

  return Man;
})();

var bob = new Man();
console.log(bob);

class Woman {
  constructor(){
    this.run = true;
  }

  isRunning() {
    console.log('yess imma run');
  }
}

var daisy = new Woman();
console.log(daisy);

Answer

It’s because methods defined in ES6 classes are non enumerable. In a Man object, isRunning is enumerable, but not in Woman. And Chrome has a specific way of handling the console log. Depending on the presence of enumerable properties or not will affect the display.

The difference in the console display is trivial, but it shows an interesting difference in the way classes are built with ES6 Class. To see it more clearly, you can try to either make Man isRunning non enumerable or Woman isRunning enumerable, it should give the same output in the console. Like this for non enumerable in Man:

var Man = (function() {
     "use strict";

     function Man() {
       this.run = true
     }

     Object.defineProperty(Man.prototype, 'isRunning', {
       value: function() {
         console.log('yesss imma run');
       },
       enumerable: false
     });

     return Man;
   })();

   
   bob = new Man();
   console.log(bob);

   class Woman {
     constructor() {
       this.run = true;
     }

     isRunning() {
       console.log('yess imma run');
     }
   }

   daisy = new Woman();
   console.log(daisy);

Or enumerable in Woman:

   var Man = (function() {
     "use strict";

     function Man() {
       this.run = true
     }

     Man.prototype.isRunning = function() {
       console.log('yesss imma run');
     };

     return Man;
   })();


   bob = new Man();
   console.log(bob);

   class Woman {
     constructor() {
       this.run = true;
     }

     isRunning() {
       console.log('yess imma run ');
     }
   }
   Object.defineProperty(Woman.prototype, 'isRunning', {
     enumerable: true
   });
   daisy = new Woman();
   console.log(daisy);

EDIT:

Note that initial drafts of ES6 had enumerable set to true by default, but it was changed, it’s a design decision. You can see discussions leading to that decision here: https://esdiscuss.org/topic/classes-and-enumerability

Basically, native prototypes usually have non enumerable methods, so it made sense to have the same behavior with user defined classes.

This decision was introduced in draft rev 32. http://wiki.ecmascript.org/doku.php?id=harmony:specification_drafts#february_2_2015_draft_rev_32

Categories
discuss

How to know if class constructor was called via super?

If I have this:

class Human {
    constructor(){

    }
}

class Person extends Human {
    constructor(){
        super();
    }
}

Is it possible to know if the Human’s constructor was called via the Person class? I thought about arguments.callee but that is deprecated.

Answer

It’s easy (but ill-advised) to check whether the instance is of a particular subclasss:

class Human {
    constructor(){
        console.log(this instanceof Person);
    }
}

To check whether it’s an instance of the base class (and not a subclass) you can use:

Object.getPrototypeOf(this) === Human.prototype

[ so long as you haven’t messed with the class and overwritten the prototype object ]

You can also check the value of this.constructor.name – it’ll reflect the type of the initial constructor called, and doesn’t change when the base class constructor is called, although this could fail if the code is minified.

Categories
discuss

Difference between Calendar.HOUR and Calendar.HOUR_OF_DAY?

What is the difference between Calendar.HOUR and Calendar.HOUR_OF_DAY ?
When to use Calendar.HOUR and Calendar.HOUR_OF_DAY ?
I am confused sometime Calendar.HOUR this works fine and othertime Calendar.HOUR_OF_DAY this works fine. What they return in the form of int?
I have read this documentation but not understood the difference.
Any suggestions
Thanks.

Answer

From http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#HOUR:

Calendar.HOUR = Field number for get and set indicating the hour of the morning or afternoon. HOUR is used for the 12-hour clock. E.g., at 10:04:15.250 PM the HOUR is 10.

Calendar.HOUR_OF_DAY = Field number for get and set indicating the hour of the day. HOUR_OF_DAY is used for the 24-hour clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.

Categories
discuss

java.lang.NoClassDefFoundError: ayc for InterstitialAd

If found that the users which use old devices (2.3.6) send me this uncatched exception:

java.lang.NoClassDefFoundError: ayc
at ajb.a(:com.google.android.gms.DynamiteModulesA:20)
at po.a(:com.google.android.gms.DynamiteModulesA:536)
at po.a(:com.google.android.gms.DynamiteModulesA:144)
at qn.a(:com.google.android.gms.DynamiteModulesA:150)
at pm.a(:com.google.android.gms.DynamiteModulesA:312)
at ul.onTransact(:com.google.android.gms.DynamiteModulesA:81)
at android.os.Binder.transact(Binder.java:279)
at com.google.android.gms.ads.internal.client.zzu$zza$zza.zzb(Unknown Source)
at com.google.android.gms.ads.internal.client.zzac.zza(Unknown Source)
at com.google.android.gms.ads.InterstitialAd.loadAd(Unknown Source)
at my.app.q.g(ABase.java:196)
at my.app.q.f(ABase.java:183)
at my.app.q.onCreate(ABase.java:88)
at my.app.AMain.onCreate(AMain.java:53)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
at android.app.ActivityThread.access$1500(ActivityThread.java:121)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3770)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:670)
at dalvik.system.NativeStart.main(Native Method)

The code at error line is this:

mInterstitialAd = new InterstitialAd(this);
//... some defenitions
AdRequest adRequest = new AdRequest.Builder().build();
mInterstitialAd.loadAd(adRequest);/// <<< THE ERROR APPEARS

Is it possible to fix this bug without wrapping try-(catch Exception e)-finally?

Answer

This is an SDK issue, rather than something wrong in your code.

The release of Play services that just rolled out contains a Mobile Ads bug that affects devices running Gingerbread. Engineering’s aware of it, a fix has been created, and it will go out in the next release.

Categories
discuss

How do I use event handlers between JavaScript module files with Node.js?

I’m currently using socket.io to emit and listen to events between a client-side JavaScript file and a Node.js server file, but I’d like to be able to emit and listen to events between the Node server and its modules. My thought is that it would look something like this:

Node server:

var module1 = require('./module1');

//Some code to launch and run the server

module1.emit('eventToModule');
module1.emit('moduleResponse', function(moduleVariable) {
   //server action based on module response
}

Module file:

var server = require('./server.js');

server.on('eventToModule', function() {
   //module response to server request
}
server.emit('moduleResponse', moduleVariable);

This is obviously a simplified version but I would think that this functionality should be available. Do I need to set up the module file as a second server? If so, what would that look like?

I also tried using var socket = io.connect('http://localhost:3000'); (this is the code I use to allow the client to connect to the Node server) instead of server and had module1 listen on and emit to socket but that didn’t work either.

SECOND ATTEMPT (still not working):

server.js

//other requirements
var module1 = require('./module');
const EventEmitter = require('events');
var emitter = new EventEmitter();

io.on('connection', function(client) {
   client.on('emitterTester', function() {
      emitter.emit('toModule');
      emitter.on('toServer', function() {
         console.log("Emitter successful.");
      });
   });
});

module.exports = emitter;

module.js

var server1 = require('./server');
const EventEmitter = require('events');
var emitter = new EventEmitter();

emitter.on('toModule', function() {
   console.log("Emitter heard by module.");
   emitter.emit('toServer');         
});

module.exports = emitter;

Also, when I try to use server1.on, I get the message server1.on is not a function.

Answer

In node.js, the EventEmitter object is typically what you use if you want to create an object that has event listeners and can then trigger events. You can either use the EventEmitter object directly or you can derive from it and create your own object that has all the EventEmitter functionality.

So, if you wanted to create a module that other modules could listen for events on, you would do something like this:

// module1.js
// module that has events

// create EventEmitter object
var obj = new EventEmitter();

// export the EventEmitter object so others can use it
module.exports = obj;

// other code in the module that does something to trigger events
// this is just one example using a timer
setInterval(function() {
    obj.emit("someEvent", someData);
}, 10 * 1000);

Then, you could have another module that uses that first one and listens for some events coming from it:

// module2.js
var m1 = require('module1.js');

// register event listener
m1.on("someEvent", function(data) {
    // process data when someEvent occurs
});

The key points here are:

  1. If you want a module to allow people to listen for events and to then trigger events, you probably want to create an EventEmitter object.
  2. To share that EventEmitter object, you assign it to module.exports or a property of module.exports so that other code that does a require() of your module can get access to the EventEmitter object.
  3. Once the calling code gets the EventEmitter object from the require(), it can then register to listen for events with the .on() method.
  4. When the original module or any module wants to trigger an event, it can do so with the .emit() method.

Keep in mind that sometimes events are a great architectural choice, but not all communication between modules is best suited to events. Sometimes, it makes sense to just export functions and allow one module to call another module’s functions. So, events are not the only way that modules can communicate with one another.


Your question seems to indicate that you think of socket.io as a way for two modules in the same server process to communicate. While it might be possible to do that, that is not normally how socket.io would be used. Usually socket.io (which is TCP/IP based) would be used for communicating between two separate processes where you do not have the luxury of making a direct function call or registering a handler for an event within your process. These latter two schemes are typically much easier for communication within a process, whereas socket.io is more typically use for communication between processes on the same computer or between processes on different computers.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..