Don P
Don P

Reputation: 63637

Javascript prototype won't update a method

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>

Upvotes: 0

Views: 89

Answers (2)

Paul S.
Paul S.

Reputation: 66334

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"

Upvotes: 2

Loamhoof
Loamhoof

Reputation: 8293

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).

Upvotes: 1

Related Questions