Domanda

In an external js (person.js) file I have something such as this:

var user = 'John';

function Person() { );

Person.prototype.sayHello = function() { 
  console.log('Hello ' + user);
}

Person.prototype.init = function() { 
  this.sayHello();
}

How can I override the sayHello method in my javascript without modifying original file? If I predefine it after loading but before calling init() it sort of works but I don't have access the user variable defined in the scope of person.js.

In another file:

Person.prototype.sayHello = function() { 
  console.log('Good morning ' + user);
}

var p = new Person();
p.init();
È stato utile?

Soluzione

var user outside any function creates a variable in the global scope, so you can access it from any other file by simply using its name.

However, if your code is running e.g. in the nodejs environment where files have their own scopes you are out or luck - JavaScript does not have nice introspection tools that let you snoop into foreign scopes.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top