HelloCW
HelloCW

Reputation: 2245

Method Inheritance Through Prototypes

I wrote the following test code, I want obj.my().showTxt() to display "test1", but nothing is displayed, what error did I make? Thanks!

<html>
<body>
Primitive and String Objects
<script type="text/javascript">

    function Class1() {
        this.showTxt = function () { alert(this.name) }
    }

    Object.prototype.my = Class1;

    var obj = new Object();
    obj.name = "test1";

    obj.my().showTxt();

</script>

</body>
</html>

Upvotes: 0

Views: 88

Answers (2)

James Hulse
James Hulse

Reputation: 1581

It seems like the problem is that your function Class1 was not returning an instance of itself.

Is this close to what you were trying to achieve?

function Class1() {
    this.show = function() {
        alert('test');
    }

    return this;
}

Object.prototype.my = Class1;

var obj = new Object();

obj.my().show();

http://jsfiddle.net/a4ZgF/

The function Class1 returns undefined (as it has no return statement). Therefore Object.prototype.my is equal to undefined which does not have a function called showTxt(). By return this you have now returned the object which has that function on it.

Using your browser's debugger will help a lot to step through each line and see what is going on.

Upvotes: 1

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107508

With a little bit of rearranging I think you can achieve what you want to do. Here's an example:

function Class1() {
    this.name = null;
}

Class1.prototype = {
    showTxt: function () { alert(this.name) }
};

var c = new Class1();
c.name = "test1";

c.showTxt();​

JSFiddle Example

Though without really knowing what you're trying to accomplish, I'm not sure what else we can do here. Are you trying to extend every single Object with a showTxt() function?

Upvotes: 0

Related Questions