Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Default property values of child Class overriding values set by parent Class' constructor #6110

Closed
derek-pavao opened this issue Dec 15, 2015 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@derek-pavao
Copy link

In my application I have a series of model classes and they all extend the same base class. The BaseClass has a constructor implemented that when given a key value map will set the values of that map on the class.

Something like:
base-class.ts

class BaseClass {
  constructor(json) {
    for (var prop in json) {
      this[prop] = json[prop];
    }
  }
}

Where my problem comes in is when extending the base class, If I define any default values for properties in the child class they will always override the values set by the constructor since I'm letting the parent class set the values, and that will always run first, then the defaults after.

For example:
Given the model person.ts

class PersonClass extends BaseClass {
  public firstName: string = 'Derek';
}

A constructed PersonClass will always have 'Derek' as the firstName value regardless of what is passed to the constructor.

i.e.

var person = new PersonClass({firstName: 'Jack'});

console.log(person.firstName); // logs Derek, not Jack

If not for the default property value being set the property would work fine. I have put together a CodePen to see a working example, http://codepen.io/dotDeeka/pen/bEErjJ?editors=001. If you view the compiled JavaScript you can see quickly that the child class calls the parents constructor before setting the default property values.

I know languages like Java require you call the parent class as the very first thing in a constructor so I'm assuming that is what you were going for here.

Any thoughts?

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Dec 15, 2015
@RyanCavanaugh
Copy link
Member

See #1617

@derek-pavao
Copy link
Author

Thanks. Sorry for the dupe.

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

2 participants