George Tsui George Tsui - 1 month ago 11
Node.js Question

Node.js : Why can't I output the create value in function()

Blow the code is my function define.

function Monster(id, name, terribleness, intelligence){
this.id = id;
this.name = name;
this.terribleness = terribleness;
this.intelligence = intelligence;
}

Monster.prototype.energy = function(){
var amount = this.terribleness * 6 + this.intelligence * 4;
console.log('Generating', amount, 'electrical energy');
}


Than, I apply content and assign Monster.prototype to james.proto.

Monster.apply(james,['1', 'James', 100, 20])
james._proto_ = Monster.prototype;


When I run this line,

james._proto_.energy()


Output:


"Generating NaN electrical energy"


why I can't get a create value 680 in the output?

Answer

The property is __proto__, not _proto_. But don't use it, not least because it's not officially supported outside of web browsers; it comes from Annex B of the spec.

In general, if you want to change the prototype of an object after creating it, that suggests you want to revisit how you created it. But it is possible, as of ES2015, with Object.setPrototypeOf:

Object.setPrototypeOf(james, Monster.prototype);

Again, this is not recommended.

I'd probably do it before calling Monster on the instance. So:

function Monster(id, name, terribleness, intelligence){
    this.id = id;
    this.name = name;
    this.terribleness = terribleness;
    this.intelligence = intelligence;
}

Monster.prototype.energy = function(){
    var amount = this.terribleness * 6 + this.intelligence * 4;
    console.log('Generating', amount, 'electrical energy');
};

var james = {}; // However it is you create it
Object.setPrototypeOf(james,  Monster.prototype);
Monster.apply(james,['1', 'James', 100, 20]);
james.energy();

Then you'd use energy on james, because it's james that has those properties on it:

james.energy();

But rather than all that, you'd be better off with simply:

james = new Monster('1', 'James', 100, 20);
james.energy();

function Monster(id, name, terribleness, intelligence){
    this.id = id;
    this.name = name;
    this.terribleness = terribleness;
    this.intelligence = intelligence;
}

Monster.prototype.energy = function(){
    var amount = this.terribleness * 6 + this.intelligence * 4;
    console.log('Generating', amount, 'electrical energy');
};

var james = new Monster('1', 'James', 100, 20);
james.energy();