简体   繁体   中英

Proper use of Class Inheritance Javascript OOP

There seems to be some problem on my syntax but I don't know what seems to be the problem.

I am using prototyping inheritance (if I'm not mistaken)

The program should be like this:

  • The class must inherit the features of the parent, so when I call on the function it will display some text.

Here is what my code looks like:

function myFunction() {

    var Property = function(dom,height,width){

        this.dom = document.createElement("img");
        this.height = height;
        this.width = width;

        };

    Property.prototype.display = function() {

    text("The image has: ", this.height+200, this.width+200);
    };

    Image.prototype = Object.create(Property.prototype)

    var firstImage = function(dom,height,width){
        Property.call(this, dom, height,width);
    };

    var image1 = new Image("image.jpg", 10 , 10);
    image1.display();
}

(I think naomik's is the better approach, but if you are trying to just figure out what's happening, see the following:)

Apparently Image does not allow extension (at least in Firefox where I am testing) because it does work with another class.

If, after this line...

Image.prototype = Object.create(Property.prototype)

...you add:

alert(Image.prototype.display)

...you will see that it is undefined, whereas if you add:

function MyImage () {}
MyImage.prototype = Object.create(Property.prototype)
alert(MyImage.prototype.display); // Alerts the "display" function

I guess that is because you cannot replace the whole prototype. Try adding to the prototype instead (though this won't help with the constructor).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM