Skip to content

Instantly share code, notes, and snippets.

@safe1981
Created March 9, 2012 00:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save safe1981/2004243 to your computer and use it in GitHub Desktop.
Save safe1981/2004243 to your computer and use it in GitHub Desktop.
Javascript: Understanding Prototype
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<script type="text/javascript">
//생성자 함수
function Foo(y){
//특정 형태의 객체를 생성합니다.
//생성된 객체는 자신의 "y" 속성을 갖게 됩니다.
this.y = y;
}
//동시에 "Foo.prototype" 은 새로 생성되는 객체의 프로토타입에 대한 참조입니다.
//즉 여기에 위의 예처럼 공유와 상속 메소드를 정의할 수 있습니다.
//상속되는 속성 "x"
Foo.prototype.x = 10;
Foo.zzz = 20;
//상속되는 메소드 "calculrate"
Foo.prototype.calculrate = function(z){
return this.x + this.y + z;
}
//"Foo" 는 "패턴"을 이용하여 "b", "c" 객체를 생성합니다.
var b = new Foo(20);
var c = new Foo(30);
//상속된 메소드를 호출합니다.
b.calculrate(30); //60
c.calculrate(40); //80
//예상대로 속성을 볼 수 있는지 표시합니다.
console.log(
b.__proto__ === Foo.prototype, //true
c.__proto__ === Foo.prototype, //true
//"Foo.prototype" 도 마찬가지로 특별한 프로퍼티 "constructor" 를 가지고 있습니다. (Foo.prototype.constructor)
//이것은 생성자 함수 자체에 대한 참조입니다.
//인스턴스 "b" 및 "c" 는 위임되어 이 속성을 참조하여 자신의 생성자를 확인할 수 있습니다.
b.constructor === Foo, //true
c.constructor === Foo, //true
Foo.prototype.constructor === Foo, //true
b.calculrate === b.__proto__.calculrate, //true
b.__proto__.calculrate === Foo.prototype.calculrate //true
);
</script>
<body>
<div id="abc">
<br />
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment