Javascript 원형 및 계승(Prototypes and Inheritance)
16374 단어 Javascript원형이어받다
///클래스 에 대한 생 성자 메 서 드 를 정의 합 니 다.
//
//각각 다른 속성 을 초기 화하 기 위해 사용 합 니 다.
functionCircle(x,y,r){
this.x = x; // The X-coordinate of the center of the circle
this.y = y; // The Y-coordinate of the center of the circle
this.r = r; // The radius of the circle
}
// Create and discard an initial Circle object.
// This forces the prototype object to be created in JavaScript 1.1.
new Circle(0,0,0);
// Define a constant: a property that will be shared by
// all circle objects. Actually, we could just use Math.PI,
// but we do it this way for the sake of instruction.
Circle.prototype.pi = 3.14159;
// Define a method to compute the circumference of the circle.
// First declare a function, then assign it to a prototype property.
// Note the use of the constant defined above.
function Circle_circumference( ) { return 2 * this.pi * this.r; }
Circle.prototype.circumference =Circle_circumference;
// Define another method. This time we use a function literal to define
// the function and assign it to a prototype property all in one step.
Circle.prototype.area = function( ) { return this.pi * this.r * this.r; }
// The Circle class is defined.
// Now we can create an instance and invoke its methods.
var c = new Circle(0.0, 0.0, 1.0);
var a =c.area( );
var p = c.circumference( ); 내 장 된 클래스 의 prototype.사용자 정의 클래스 뿐만 아니 라 prototype.시스템 내 장 된 클래스,예 를 들 어 String,Date 도 있 습 니 다.그리고 그들 에 게 새로운 방법,속성 등 을 추가 할 수 있다.다음 코드 는 모든 String 대상 에 유용 한 함 수 를 추가 합 니 다:
//Returns true if the last character is c
String.prototype.ends With=function(c){
return(c==this.charAt(this.length-1))
}그리고 우 리 는 이와 유사 하 게 호출 할 수 있 습 니 다.
var message="hello world";
message.endsWith('h') // Returns false
message.endsWith('d') // Returns true
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Javascript에서 Math.max와 Math.max.apply의 차이점과 용법 상세 설명최근에 작은 사례를 만들 때 Math를 만났어요.max.apply라는 용법은 이전에 보기 드물게 재미있게 느껴졌으니 기록해 보세요. 1Math.max 문법:Math.max(n1,n2,n3,...,nX)반환값:max(...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.