Skip to content Skip to sidebar Skip to footer

Why Cant I Declare A Constructor Instantiate An Object And Then Access The Prototype?

The below doesnt work and im struggling to work out why.... function CommentHandler() { var Text; } var myCommentHandler = new CommentHandler(); myCommentHandler.prototype.

Solution 1:

The prototype belongs to the class, not the instance:

CommentHandler.prototype.MyFunction = ...

However you can also access the prototype via the instance's constructor property:

myObj.constructor.prototype.MyFunction = ...

This will of course add that function to every instance of your CommentHandler.

If instead you only wanted to add that function to that one instance, you'd do:

myObj.MyFunction = ...

Note that in none of these variants would it be possible for MyFunction to access your private variable Text.

This is the compromise forced by the prototype inheritance model - variables and methods must be public (e.g. this.Text) if they're to be accessed from outside, and in this case functions declared in the prototype are effectively "outside".

The alternative (using closure-scoped variables and methods) seems more natural to OO programmers, but makes inheritance much harder.

Solution 2:

I think what you actually want here is this:

CommentHandler.prototype.SayHello = function () {
    document.write('Hello World');
};

Solution 3:

You have to use

CommentHandler.prototype.SayHello = function(){....}

You can find more about the prototype object in the following references http://www.javascriptkit.com/javatutors/proto.shtmlhttps://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/prototypehttp://msdn.microsoft.com/en-us/magazine/cc163419.aspx

Solution 4:

You need to prototype the class function rather than the instance. Also if you want the Text variable to be accessible outside the constructor, in the other method functions, then you need to add the this keyword.

functionCommentHandler() {
    this.Text = 'Hello World';
}

CommentHandler.prototype.SayHello = function () {
    document.write(this.Text);
}

var myCommentHandler = newCommentHandler();
myCommentHandler.SayHello();

As a side point you could create the SayHello function inside the constructor, but this would add increased overhead to the creation of each instance of CommentHandler. Thus the prototyping method that you are using is a better option.

Solution 5:

myCommentHandlerdoes not have a prototype, because it is an instance. CommentHandlerdoes have a prototype that can be modified. I am guessing you want to edit the object after initializing, and can do so like this:

myCommentHandler.SayHello = function() {
    document.write('Hello World');
}

Here is a good explanation of prototypes and object oriented programming in javascript with many examples: http://mckoss.com/jscript/object.htm

Post a Comment for "Why Cant I Declare A Constructor Instantiate An Object And Then Access The Prototype?"