IT/JavaScript
new 메소드( Function을 new하게 되면 안에서 행해지는 모습들)
트래이닝맨
2012. 8. 10. 10:03
728x90
반응형
function을 new하는 메소드는 어떻게 생겼을까?
Source if(typeof Object.create !== 'function'){ var Object = function(o){ return { create:function(){ var F = function(){}; F.prototype = o; return new F(); } } }; } Function.prototype.kkk = function() { var that = Object.create(this.prototype); var other = this.apply(that, arguments); return (typeof other === 'object' && other) || that; }; function add() { return "aaa"; } var a = add.kkk(); alert(a); |
kkk() 메소드 설명 Function.prototype.kkk = function() { var that = Object.create(this.prototype); //kkk를 호출하는 function이 this가 된다. that은 this의 prototype이 가리키는 object를 바라보는 새로운 빈 object가 된다. var other = this.apply(that, arguments); //this //other 는 kkk를 호출했던 function을 실행시키다. return (typeof other === 'object' && other) || that; //null은 falsy를 의미함. 따라서 여기서의 조건은 function을 호출한 값의 type이 object인지 그리고 그 값이 null인지 체크하는 것이다. }; 만약에 리턴 값이 object가 아니라면 무조건 새로 만들어진(그전 function을 hidden link로 가리키고 있는) object 를 넘기게 되는 것이다. |
반응형