Massimo Modica
Massimo Modica

Reputation: 47

Different behaviour after copying methods

I was expecting the same behaviour from getName2 and getName3, but getName3 throws an error (prints 'The Window' in non-strict mode)

"use strict";

var name = 'The Window';
var object = {
    name : 'The Object',
    getName: function(){
        alert(this.name);
    }
};

object.getName();    // The Object

object.getName2 = object.getName;
object.getName2();    // The Object

(object.getName3 = object.getName)(); // Error: TypeError: this is undefined

This code is derived from an example in Chapter 7 of Professional Javascript for Web Developers by N.Zakas.

Upvotes: 0

Views: 46

Answers (1)

James Allardice
James Allardice

Reputation: 166021

The context of a function depends on how it is called. In your final example, you use a grouping operator (a pair of parentheses) which returns a reference to the function referred to by object.getName. It loses the context of object.

When you then invoke that function, since it's lost the context of object and you're running in strict mode, the context becomes the global object and this is undefined. You can force that function to run in the context of object by, for example, explicitly binding it to it:

(object.getName3 = object.getName).bind(object)(); // The Object

Upvotes: 2

Related Questions