JavaScript 원형 과 원형 체인
3414 단어 JavaScript
var arr1 = [10, 20, 30, 40, 50];
var arr2 = [1, 2, 3, 4, 5];
// ,
arr1.sum = function(){
var num = 0;
for(var i = 0; i < this.length; i++){
num += this[i];
}
return num;
}
alert(arr1.sum());//150
alert(arr2.sum());// arr2.sum is not a function
alert(arr1.sum == arr2.sum);//false
모든 배열 의 대형 이 구 와 함 수 를 가지 게 하려 면 우리 의 함 수 는 구조 함수 의 원형 에 추가 해 야 합 니 다.Array. prototype (원형 대상).
var arr1 = [10, 20, 30, 40, 50];
var arr2 = [1, 2, 3, 4, 5];
Array.prototype.sum = function(){
var num = 0;
for(var i = 0; i < this.length; i++){
num += this[i];
}
return num;
}
alert(arr1.sum());//150
alert(arr2.sum());//15
alert(arr1.sum == arr2.sum);//true
2. instanceof instanceof 연산 자 는 실행 할 때 대상 이 특정 클래스 인지 아 닌 지 를 지적 하 는 인 스 턴 스 입 니 다.instanceof 는 불 값 을 되 돌려 서 이 대상 이 특정한 클래스 나 하위 클래스 의 인 스 턴 스 인지 여 부 를 지적 합 니 다.proto__속성, 구조 함수 의 prototype 속성 을 가리킨다.
function Person(name, sex){
//
this.name = name;
this.sex = sex;
}
//
Person.prototype.showName = function(){
alert(" " + this.name);
}
Person.prototype.showSex = function(){
alert(" " + this.sex + " ");
}
var p1 = new Person(" ", " ");
alert(p1 instanceof Person);//true
3、–proto–
function Person(name, sex){
//
this.name = name;
this.sex = sex;
}
//
Person.prototype.showName = function(){
alert(" " + this.name);
}
Person.prototype.showSex = function(){
alert(" " + this.sex + " ");
}
var p1 = new Person(" ", " ");
alert(p1.__proto__);//[object Object]
alert(p1.__proto__ == Person.prototype);//true
4. 정리 해 보 세 요. js 중의 를 정리 해 야 할 때proto__prototype 과 의 링크 순 서 는 기억 하 세 요.
(1) 함수 대상 은proto__prototype 속성 (2) 비 함수 대상 은 밖 에 없습니다.proto__속성 (3) prototype 중proto__속성또한 Object 구조 함수 가 만 든 (4) 함수 대상proto__그것 을 가리 키 는 창조 자 및 Function 구조 함수 (5) Function 구조 함수proto__자신 을 가리 키 는 (6) Object 대상 의 prototype 중의proto__null
5. 원형 체인 을 사용 하여 계승 실현
for(var funcName in Person.prototype){
Worker.prototype[funcName] = Person.prototype[funcName];
}//
6. constructor 방법 은 기본적으로 인 스 턴 스 대상, 즉 this 를 되 돌려 줍 니 다.다른 대상 으로 돌아 갈 수도 있다.
/*
ECMA6class
*/
class Phone{
constructor(size,color){
this.size = size;
this.color = color;
}
show(){
alert(` ${this.color} ,${this.size}GB `);
}
}
class PhoneX extends Phone{
constructor(size,color,type){
//
super(size,color);
this.type = type;
}
showSelf(){
alert(` ${this.type} `);
this.show();
}
}
var iphoneX = new PhoneX(256, " ", "xsMax");
iphoneX.showSelf()
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
기초 정리 - 1문자 (String) 숫자 (Number) 불린 (Boolean) null undefined 심볼 (Symbol) 큰정수 (BigInt) 따옴표로 묶어 있어야 함 Not-A-Number - 숫자 데이터 / 숫자로 표...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.