2

I have a Pers(on) and an Employee, who is derived from Pers.

Pers = function(options){
  this.Name;
  this.ID;
  this.init = function(options){
    this.Name=options.Name;
    this.ID=options.ID;
  }
}

Employee = function(options){
  this.Sal;
  this.init = function(options){
    this.Sal=options.Sal;
    this.__proto__.init(options);
  }
  this.init(options);
}

Employee.prototype=new Pers();

Now when i create new objects...

var o=new Employee({Name:"Nik",ID:"1",Sal:100});
var p=new Employee({Name:"Tanja",ID:"2",Sal:200});

and alert their Name, i will get two times "Tanja".

Has anyone an idea?

1
  • 3
    Pretty sure you shouldn't be using __proto__ anymore. Commented Jul 17, 2012 at 16:11

2 Answers 2

3
this.__proto__.init(options);

will call the init method on the prototype with the prototype itself as this, causing you to modify the prototype. Try

this.__proto__.init.apply(this, [options]);

Edit

To avoid __proto__ you can save a reference to the prototype init function before you shadow it:

Employee = function(options){
  this.Sal;
  var protoInit = this.init;
  this.init = function(options){
    this.Sal=options.Sal;
    protoInit.apply(this, [options]);
  }
  this.init(options);
}
Sign up to request clarification or add additional context in comments.

1 Comment

call(this, options) is probably better in this case
2

You're calling init in the wrong scope. Try something like this.

function Person(opt) {
    this.name = opt.name;
    this.id = opt.id;
}

function Employee(opt) {
    Person.call(this, opt);
    this.sal = opt.sal;
}

Employee.prototype = Object.create(Person.prototype, {});

You can now set properties of Person.prototype and Employee.prototype and they should behave as expected.

This avoids using hacky deprecated properties (__proto__) and should be a lot clearer. Object.create is used to make an instance using the super-constructor's prototype without actually calling the super-constructor (removing the need for init calls). You could include semi-standard property definitions such as super and constructor while you're doing it, as many libraries' inherits implementations do.

2 Comments

this is not working, when i'm creating new objects: var o=new Employee({name:"Nik",id:"1",sal:100}); var p=new Employee({name:"Tanja",id:"2",sal:200}); o.name will not be found. what i'm doing wrong?
In my haste to re-write without init, I made the same mistake you did. Answer edited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.