Node.js 외부 Javascript 파일 연동 관련
2017. 8. 28. 10:44ㆍ서버 프로그래밍
Node.js를 사용하여 웹과 서버프로그램 동시에 사용 가능한 코드 개발하기
http://blog.saltfactory.net/using-single-javascript-code-on-front-and-server-side/
/**
* filename : person.js
*/
var Person = function (name) {
this.name = name;
this.hello = function () {
return "Hello, My name is " + this.name + "!";
}
}
node 쉘에서 다음 코드를 실행한다.
var fs = require('fs');
eval(fs.readFileSync('person.js', 'utf-8'));
var saltfactory = new Person("SungKwang");
var mushroom = new Person("YoungJi");
console.log(saltfactory.hello()):
console.log(mushroom.hello());
* callback에서 this를 사용하는 것 때문에 불필요하게 시간 낭비를 했다. ㅠㅠ
https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback
How to refer to the correct this
Don't use this
You actually don't want to access this
in particular, but the object it refers to. That's why an easy solution is to simply create a new variable that also refers to that object. The variable can have any name, but common ones are self
and that
.
function MyConstructor(data, transport) {
this.data = data;
var self = this;
transport.on('data', function() {
alert(self.data);
});
}
Since self
is a normal variable, it obeys lexical scope rules and is accessible inside the callback. This also has the advantage that you can access the this
value of the callback itself.