다른 인스턴스의 개인 상태를 상속 받기를 원하십니까? JavaScript에서이 작업을 수행 할 수 있습니다. 다음과 같이
var Dog = (function() {
function Dog() {
if (this instanceof Dog) {
// constructor code
} else return Object.create(private);
}
var public = Dog.prototype, private = Object.create(public, {
size: {
value: "big"
}
});
public.saySize = weakBind(function (private) {
return "I am a " + private.size + " dog.";
}, public, private);
return Dog;
}());
지금 당신은 개를 만들 수 있습니다 다음과 같이
function weakBind(functable, prototype, state) {
return function() {
return functable.apply(this, Object.getPrototypeOf(this) === prototype ?
[state].concat(Array.prototype.slice.call(arguments)) : arguments);
};
}
이제 우리는 우리의 기본 클래스를 생성 할 수 있습니다 : 처음에 우리는 유틸리티 함수를 정의 할 필요가
var dog = new Dog;
alert(dog.saySize()); // I am a big dog.
alert(dog.size); // undefined
을 우리 다음과 같이 개인 상태를 상속 할 수 있습니다.
var Chihuahua = (function() {
function Chihuahua() {
Dog.call(this);
}
var private = Dog();
Object.defineProperty(private, {
size: {
value: "small"
}
});
var public = Chihuahua.prototype = Object.create(Dog.prototype);
public.saySize = weakBind(public.saySize, public, private);
return Chihuahua;
}());
다음과 같이 (210)
이제 치와와를 만들 수 있습니다
var chi = new Chihuahua;
alert(chi.saySize()); // I am a small dog.
alert(chi.size); // undefined
데모를 참조하십시오 http://jsfiddle.net/b3Eyn/
참고 :가 난 그냥 자바 스크립트에서 개인 상태를 상속 할 수 있다는 표시하려면이 대답을 썼다. 그러나 나는이 패턴을 사용하지 말 것을 권고합니다. 코드를 잘 디자인하면 처음부터 개인 상태를 상속받을 필요가 없습니다.
이 함수는 무엇입니까? Dog = (function() {})()'? – Amberlamps
'private' 멤버는 OOP를 지원하는 _any_ 언어로 정의 된 클래스 안에서 _only_ 볼 수 있습니다. 나는 네가하려는 일을 못 얻는다. – Leri
일반적으로는 아니지만 '비공개 기능'은 'notSoPrivateSaySize = new Dog()'를 통해 쉽게 접근 할 수 있습니다.publicSaySize();' – Bergi