2016-11-12 1 views
1

코드에 대한 몇 가지 질문이 있습니다.자바 스크립트에서 생성자와 호출 방법

1) 학생 생성자에서 Person.call (this, firstName)에게 학생의 방법에 대한 액세스 권한을 부여합니까? 또는 의 컨텍스트를 변경합니까?

2) 나는 Student.prototype = Object.create (Person.prototype)가 person의 메소드와 속성에 접근 할 수 있다고 가정한다.

통화 방법을 이해하는 데 어려움을 겪고 있습니다.

var Person = function(firstName) { 
    this.firstName = firstName; 
}; 

Person.prototype.walk = function(){ 
    console.log("I am walking!"); 
}; 


function Student(firstName, subject) { 
    Person.call(this, firstName); 
    this.subject = subject; 
}; 

Student.prototype = Object.create(Person.prototype); // See note belo 
Student.prototype.constructor = Student; 

Student.prototype.sayHello = function(){ 
    console.log("Hello, I'm " + this.firstName + ". I'm studying " 
       + this.subject + "."); 
}; 

답변

0

1) 아니, 그것은 this 값을 설정하고 인수를 전달하지만 this 내부 Student 무엇이든에 Personthis 값을 설정, 그것은 또한 PersonStudent에 액세스 할 수 있지만, 다른되지를 줄 수 길 주변에.

모두 call(this-value, [arg1,arg2])apply(this-value, [[arg1,arg2]])은 주어진 값과 인수로 함수를 호출합니다.

2) 예 Student.prototype = Object.create(Person.prototype) 복사 Person의 프로토 타입과 같은 PersonStudent 프로토 타입을 동일한 방법을 제공 Student의 원형으로 설정하지만 복사하지 동일한 참조.

+0

감사합니다 adeneo 훌륭한 설명! 몇 가지 질문이 더 있습니다. var student1 = new Student ("john", "physics")를 만들면; student1 객체가 생성되면 'this'(student1)과 john이라는 이름으로 전달되는 person 함수를 호출합니다. 그래서 우리는 person1 객체 외부의 함수를 호출하여 함수를 공유 할 수있게했습니다. – stckpete

관련 문제