Search code examples
javascriptnode.jsanonymous-functionobject-literal

Another brick in the JS wall


I must confess, JavaScript has -sometimes- strange behaviors.

var Npc = function() {
    this.name='Hello world';
}

Npc.attr='my new attribute';

console.log('>>>>'+Npc.attr);               // my new attribute
console.log('>>>>'+Npc.name);               // '' ????

var data = new Npc();

console.log('>>>>>' + data.attr);           // undefined
console.log('>>>>>' + data.name);           // Hello world

Sounds weird to me. If I can understand the .name difference (instance vs literal), I cannot understand the "attr" behavior.

Is it a COW ? But with the node.js debugger I really see the attr atribute !?

Waw...


Solution

  • If you're coming from a class-keyword language like Java or C++, then this might help you.

    In JavaScript a function can be used as a constructor for an object, as you did here:

    var Npc = function() {
        this.name='Hello world';
    }
    var data = new Npc();
    

    By way of loose analogy to a class-keyword language, the "name" property is an instance variable defined in a "class" called Npc. So the expression data.name is perfectly logical.

    In JavaScript a function is also an object, which is how you used it here:

    Npc.attr='my new attribute';
    

    Again by way of loose analogy to a class-keyword language, Npc.attr is like a static class member. So attr is a member of Npc and not a member of any instance of Npc.