0

I'm learning to use javascript's prototype feature (not the library). I thought I could replace an object's method by using MyObject.prototype.myFunction = function () { ... }. Apparently this doesn't work.

The code below defines an object, and replaces its function using prototype. Run it in your browser, the console still shows the original output.

    <script type="text/javascript">
        function TestObject() {
            this.testFunction = function() {
                console.log("Original function output");
            }
        }

        // This should replace the method defined in the object.
        TestObject.prototype.testFunction = function() {
            console.log("YOU GOT CHANGED");
        }

        var HelloWorld = new TestObject();

        HellowWorld.testFunction(); // Should output "YOU GOT CHANGED"
    </script>
1
  • 4
    The instance method shadows any prototype method. Commented Apr 8, 2013 at 17:22

2 Answers 2

2

Instance methods shadow methods inherited through the prototype chain

var HelloWorld = new TestObject();
HelloWorld.testFunction(); // finds method on instance
// "Original function output"
delete HelloWorld.testFunction; // delete method from instance
HelloWorld.testFunction(); // not found on instance, look in prototype, found
// "YOU GOT CHANGED"
Sign up to request clarification or add additional context in comments.

Comments

1

Not really, in your constructor, you're overriding the prototype. The original code is the prototype's one (it's bound as soon as you create the object, before running it).

1 Comment

When you say "it's bound", what are you referring to?

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.