문제

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();
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top