2013-03-21 2 views
1

나는 Require.js를 잘 이해하지 못하기 때문에 아래 예제에서 (전 세계적으로) firstName과 lastName을 왜 바꿀 수 있는지 묻고 싶습니다.Requirejs 및 전역 범위 오염 방지

Require.js가 전역 범위를 오염시키지 않도록해야합니까? 객체 변경을위한 인터페이스를 제공하는 것뿐입니다. 고마워.

// someModule.js 
define([], function() { 
    function Employee(firstName, lastName) { 
     this.firstName = firstName; 
     this.lastName = lastName;   
    } 

    Employee.prototype.getName = function() { 
     return this.firstName = ' ' = this.lastName; 
    } 

    return { 
     createEmployee: function(fName, lName) { 
      return new Employee(fName, lName); 
     }; 
    }; 
}); 

// main.js 
require(['jquery', 'someModule'], function($, someModule) { 
    $(function() { 
     var x = someModule.createEmployee('John', 'Doe'); 
     document.write(x.getName() + '<br>'); 
     x.firstName = 'Some other name'; 
     x.lastName = 'Some other surname'; 
     document.write(x.getName()); 
    }); 
}); 

그리고 출력은 다음과 같습니다
홍길동
몇 가지 다른 이름을 여기에 전역 범위를 polute하지 않는

+5

이미지 링크가 아닌 코드를 게시하는 것이 좋습니다. –

답변

2

당신은 속성의 가시성으로 글로벌 누출을 혼동하고 있다고 생각합니다. firstNamelastName은 누출 된 이 아니며 공개적으로 액세스 할 수 있으며 수정할 수 있습니다 (변경 가능). 이미지를 숨기려면 다음과 같이 할 수 있습니다.

function Employee(firstName, lastName) {  
    this.getFirstName = function() { return firstName; }; 
    this.getLastName = function() { return lastName; }; 
} 

Employee.prototype.getName = function() { 
    return this.getFirstname() + ' ' + this.getLastName(); 
}; 
+0

[Understanding JavaScript OOP] (http://killdream.github.io/2011/10/09/understanding-javascript-oop.html) 링크가 변경되었습니다. – Vlad

+0

두 링크가 모두 종료되었으며 미러를 찾을 수 없습니다. , 그래서 그것을 제거했습니다 : ( – c24w

+0

게시물의 캐시 된 복사본을 사용할 수 있습니다 [여기] (http://web.archive.org/web/20131120224629/http://killdream.github.io/2011/10/09/understanding -javascript-oop.html). – c24w

1

다른 어떤 성 - 코드는 익명 함수 (폐쇄) 아무것도 내에서 실행이 윈도우 전역 객체에 바인딩하십시오.

1

생성 된 개체의 속성은 "firstName"및 "lastName"입니다. 코드는 이러한 속성을 수정하지 못했습니다.

새로운 JavaScript 구현에서는이를 수행 할 수있는 방법이 있지만 Requirejs는 자동으로 수행하지 않습니다 (중요한 재 설계 또는 개선 프로젝트가 없어도 최소한).

특히 defineProperty 메서드를 사용하면 읽기 전용 속성을 만들 수 있습니다. 이제는 모두 코드가 속성을 수정하지 못하게됩니다. 객체의 제어를받는 속성을 원한다면 @ c24w가 다른 대답에서 제시하는 것과 같은 기술을 사용할 수 있습니다.

+0

Employees의 속성을 직접 액세스하지 못하도록 보호하는 방법을 알려주십시오. 감사. – Srle

+0

'defineProperty' 또는'defineProperties'를 사용할 때'writable' 키를 false로 설정하는 것은 좋은 해결책입니다 (역 호환성이 문제가되지 않는다면). – c24w