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

Don't return a value from parent constructor call #555

Closed
billyzkid opened this issue Aug 11, 2011 · 1 comment
Closed

Don't return a value from parent constructor call #555

billyzkid opened this issue Aug 11, 2011 · 1 comment

Comments

@billyzkid
Copy link

From the "inherits" function:

if (protoProps && protoProps.hasOwnProperty('constructor')) {
    child = protoProps.constructor;
} else {
    child = function(){ return parent.apply(this, arguments); };
}

Proposed fix:

if (protoProps && protoProps.hasOwnProperty('constructor')) {
    child = protoProps.constructor;
} else {
    child = function(){ parent.apply(this, arguments); };
}

Note the "return" statement used in the current code vs. the proposed fix. A constructor function called by itself (without new) should never return a value. But even if users avoid return values from their own constructors, I can think of at least one bug this might cause, or at least one nice feature this would allow if the above code were changed to avoid a return value.

For example, to leverage inheritance in Backbone, currently I must extend Backbone.Model (or Collection, View, etc.). However, what if I just wanted to define a minimal set of classes that extend Object. I might try this:

// let anything to be extended
Object.extend = Backbone.Model.extend;

// namespace
var Acme = {};

// define classes
Acme.Person = Object.extend();
Acme.Warrior = Acme.Person.extend();
Acme.Ninja = Acme.Warrior.extend();

// instantiate
var mary = new Acme.Person();
var will = new Acme.Warrior();
var john = new Acme.Ninja();

// unit tests
ok(mary instanceof Object && mary instanceof Acme.Person && mary.constructor === Acme.Person);
ok(will instanceof Object && will instanceof Acme.Person && will instanceof Acme.Warrior && will.constructor === Acme.Warrior);
ok(john instanceof Object && john instanceof Acme.Person && john instanceof Acme.Warrior && john instanceof Acme.Ninja && john.constructor === Acme.Ninja);

The unit tests fail when the return statement is used. However, if you remove the return from your parent constructor call, then all tests will pass.

In other words, if this change is made, then we can also use Backbone to define simple class inheritance without using Backbone-specific classes.

@jashkenas
Copy link
Owner

Good idea -- changed as you request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants