Web/자바스크립트

자바스크립트_this

davisasan 2018. 3. 28. 00:39
<<이글은 생활코딩을 실습, 정리한 내용입니다. 이고잉님 감사^^>>

객체란 서로 연관된 변수와 함수를 그룹핑한 그릇이라고 할 수 있다. 객체 내의 변수를 프로퍼티(property), 함수를 메소드(method)라고 부른다. 객체를 만들어보자.


1#
var person = {}; // var Person = new person(); 와 같은 효과이다. 즉 person이 객체
person.name = 'jasonkim';
person.introduce= function(){ 
return this.name;   // this 는 객체인 person 이다.
 console.log(this.name);  



   person.introduce()
   //"jasonkim"


 2#

var person = {};        // var Person = new person(); 와 같은 효과이다. 즉 person이 객체
     person.name = 'jasonkim';
     person.introduce= function(){
        console.log( this.name);         

      }

 person.introduce() 
   //"jasonkim"




 중복이 존재한다.#
function Person(){}
var p1 = new Person();
p1.name = 'egoing';
p1.introduce = function(){
return 'My name is '+this.name;
}
p1.introduce();
var p2 = new Person();
p2.name = 'leezche';
p2.introduce = function(){
return 'My name is '+this.name;
}
p2.introduce(0);



중복을 없애고 수정#

function Person(name){
this.name = name;
this.introduce = function(){
return 'My name is '+this.name;
}
}
var p1 = new Person('egoing');
p1.introduce();
var p2 = new Person('leezche');
p2.introduce();






  this와 생성자#

var FuncThis = null;

function Func(){
   FuncThis = this;
}
var o1 = Func();           // Func()함수의 객체는 window이다.
if(FuncThis == window){
   console.log( "this는 Window");

}

var o2 = new Func();   // Func() 함수의 객체는 o2이다. 
if(FuncThis == o2){
    console.log("this는 FunThis")

  }


   //this는 Window
   //this는 FunThis





this연습 #3

var FuncThis = null;      
function Func(){
      FuncThis = this;       // this는 p이다.
      console.log(p);
}

var p = new Func();  // Func()함수의 객체는 p이다.

// Func {}


function Func(){ 
     console.log(o);      //   o는 아직 할당이 되지 않음 undefined !
}

var o = new Func();    // Func()함수의 객체는 o이다.



2#

function Func(){ 
     console.log(this);      //   this는 p이므로 아래처럼 출력된다.
}

var o = new Func();    // Func()함수의 객체는 o이다.



//Func {}




=> 함수가 window 나 o ,  p와 같은 객체를 만나면 메소드가 된다. 

      func()는 함수이므로 this 에는 window 가 들어간다. 아직 생성자를 객체화시키지 않았기에...
      Func.apply(o) 는 Func이라는 객체가 갖고있는 apply()메소드를 통하여 o가 this에 들어간다.
      
       즉, 함수가 객체화 되면 그 객체의 메소드로 살아가게 된다.




상속#

function Person(name){
  this.name = name;

 //  생성자이며 this는 p1객체이다.

Person.prototype.name = null;                                
Person.prototype.introduce = function(){
        return 'My name is'+ this.name;
}
 // prototype 속성안에 name과 introduce 속성생성

var p1 = new Person('jasonkim');
  p1.introduce()
 
// 객체생성하고 출력

//"My name isjasonkim"





상속코드#

에러발생코드
function Person(name){
  this.name = name;
}  
 //  생성자이며 this는 p1객체이다.

Person.prototype.name = null;                                 
Person.prototype.introduce = function(){
        return 'My name is'+ this.name;
}
 // prototype 속성안에 name과 introduce 속성생성


function Programmer(name){
   this.name = name;
}


Programmer.prototype.name = null;  // 버그 삭제

Programmer.prototype.coding = function(){
return "hello world"; // 상속후에 써주기
}

Programmer.prototype = new Person(); // 버그 :순서가 생성자바로아래임
  //상속


var p1 = new Programmer('jane');
 p1.introduce()

 p1.coding()



 수정#
//"My name isjasonkim"

function Person(name){
  this.name = name;
}  
 //  생성자이며 this는 p1객체이다.

Person.prototype.name = null;                                 
Person.prototype.introduce = function(){
        return 'My name is'+ this.name;
}
 // prototype 속성안에 name과 introduce 속성생성


function Programmer(name){
   this.name = name;
}


Programmer.prototype.name = null;  // 버그 삭제

Programmer.prototype = new Person(); // 버그 :순서가 생성자바로아래임
 
Programmer.prototype.coding = function(){
        return 'Hello jane';
  }

var p1 = new Programmer('jane');
 p1.introduce()

 p1.coding()


//"Hello jane"




에러발생#
function Person(name){
  this.name = name;
}  
 //  생성자이며 this는 p1객체이다.

Person.prototype.name = null;                                 
Person.prototype.introduce = function(){
        return 'My name is'+ this.name;

function Programmer(name){
     this.name = name;

Programmer.prototype = new Person();
}   // 이것때문에 버그!  타자잘치자!
var p1 = new Person('jasonkim');
  p1.introduce();

var p2 = new Programmer('jane');
  p2.introduce();
 


참고

The Property (object attribute)

속성은 클래스 안에 있는 변수들을 말한다. 객체의 모든 인스턴스는 그 인스턴스의 속성을 갖는다. 속성들의 상속이 바르게 이루어지려면 해당 클래스(function)의 프로토타입에 선언되어 있어야 한다.
 
클래스 내에서 속성 작업은 현재 객체를 가리키는 this 키워드에 의해 이루어진다. 클래스의 외부에서 속성에 접근(읽기 혹은 쓰기)하는 것은 "인스턴스이름.속성명" 의 형식으로 이루어진다. 이러한 문법은 C++, 자바나 다른 수많은 언어에서와 동일한 방식이다. (클래스 내부에서 "this.속성명" 은 해당 속성의 값을 읽거나 쓸때 주로 사용된다)
 
아래의 예제에서 Person 클래스에 gender 라는 속성을 정의하고 인스턴스화할 때 그 값을 설정한다.
function Person(gender) {
  this.gender = gender;
  alert('Person instantiated');}

var person1 = new Person('Male');var person2 = new Person('Female');
//display the person1 gender
alert('person1 is a ' + person1.gender); // person1 is a Male