0

I have the next code with inheritance.

function FileS(){}
FileS.prototype.getS = function (num){
    console.log(num);
}
FileS.prototype.getDynamic = function(){
 // WHAT I need to write here, so the function would call the DYNAMIC function
}

S3.prototype= new Files();
S3.prototype.constructor = S3();
function S3(){}
S3.prototype.getS = function (num){
     console.log("This is for S3: " + num);
}

function dataE(u){
   var s3 = new S3();
   s3.getDynamic();
}

As I understand, s3 will call to FileS.protortpe.getDynamic, because it hasn't this function in S3 prototype. But now, I want that FileS.protortpe.getDynamic will call to s3.protortpe.getS, if the type is S3, and FileS.prototype.getS otherwise. How can I do it (without specify s3 or FileS, because that is more types..)?

2
  • 1
    This isn't right S3.prototype.constructor = S3();. You want to assign a reference to the function, not an instance or return value. Commented May 5, 2014 at 8:17
  • 2
    And using new Files to create S3's prototype is an anti-pattern. Commented May 5, 2014 at 8:18

1 Answer 1

2

Here's the correct way to set up a prototype hierarchy using constructor functions:

// ==== FileS ====
function FileS() {
}
// Add any FileS prototype things to `FileS.prototype`

// ==== S3 ====
function S3() {
    FileS.call(this); // You could pass args here if appropriate
}
S3.prototype = Object.create(FileS.prototype);
S3.prototype.constructor = S3; // Optional, but a good idea
// Add any S3 prototype things to `S3.prototype`

...where we shim the single-argument version of Object.create if necessary for older browsers, like this:

if (!Object.create) {
    Object.create = function(proto, props) {
        if (typeof props !== "undefined") {
            throw "The multiple-argument version of Object.create cannot be shimmed.";
        }
        function ctor() { }
        ctor.prototype = proto;
        return new ctor();
    };
}

Because that's a fair bit of boilerplate, I have a small helper script called Lineage to do it for me. these days I use ES2015's class syntax and a transpiler like Babel.

Sign up to request clarification or add additional context in comments.

2 Comments

But how the call to GerS is changed according to specific type? If the type S3, it should go to the function of S3, and Otherwise to FileS. And this I know just when I run my program.
@OrSmith: Where I've said "Add any XX prototype things to XX.prototype" above, that's where you'd put the getS function for each type. An object created with new S3 will get S3's version; an object created with new FileS will get FileS's version.

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.