객체 지향 프로그래밍 (OOP)은 프로그래밍 패러다임이자 프로그램 개발 방법입니다. 객체는 클래스 인스턴스를 나타냅니다. 소프트웨어의 재사용 성, 유연성 및 확장 성을 향상시키기 위해 객체를 프로그램의 기본 단위로 사용하고 프로그램 및 데이터를 캡슐화합니다. -Wikipedia
일반적으로 객체 지향에는 상속, 캡슐화, 다형성, 추상화가 포함됩니다
객체 형태의 상속
라이트 카피
var person = {name : 'Allin', Age : 18, 주소 : {home : 'home :'Office : 'Office', 'Office', '} sclools : ['x ','z '],}; var 프로그래머 = {언어 :'js ',}; 함수 확장 (p, c) {var c = c || {}; for (p in p) {c [prop] = p [prop]; }} extend (person, program); veradier.name; // AllInProgramer.address.home; // HomeProgramer.address.home = 'House'; //houseperson.address.home; // 집위의 결과로부터 얕은 사본의 결함은 자식 객체의 기준 유형 값을 수정하면 참조 유형의 얕은 사본에서 주소 만 복사하고 메모리의 동일한 사본을 가리키기 때문에 부모 객체의 값에 영향을 미친다는 것입니다.
딥 카피
함수는 ExtendDeeply (P, C) {var c = c || {}; for (p) {if (typeof p [prop] === "object") {c [prop] = (p [prop] .constructor === array)? [] : {}; ExtendDeeply (P [Prop], C [Prop]); } else {c [prop] = p [prop]; }}}심층 복사를 위해 재귀를 사용하여 하위 객체의 수정이 부모 객체에 영향을 미치지 않습니다.
ExtendDeeply (Person, Progracer); 프로그래머 .address.home = 'Allin'; person.address.home; // 홈을 사용하여 호출을 사용하여 기능을 상속합니다. this.address = {home : "home"};} function child () {parent.call (this); this.language = "js"; } object.create ()에서 es5 var p = {name : 'allin'}; var obj = object.create (o); obj.name; // AllinObject.create () 새 연산자의 대안으로 ES5 이후에만 해제됩니다. 우리는 또한이 방법을 스스로 시뮬레이션 할 수 있습니다.
// 객체를 시뮬레이션합니다. F. 프로토 타입 = O; o = 새로운 f (); return o;} var p = {이름 : 'Allin'}; var obj = myCreate (o); obj.name; // Allin현재 IE9 포함 된 주요 브라우저의 최신 버전 이이 방법을 배포했습니다. 이전 브라우저가 발생하면 다음 코드를 사용하여 직접 배포 할 수 있습니다.
if (! object.create) {object.create = function (o) {function f () {} f.prototype = o; 새로운 f ()를 반환합니다. }; }수업 상속
Object.create () 함수 사람 (이름, 연령) {} person.pherotyp.headcount = 1; person.prototyp.eat = function () {console.log ( 'Eating ...');} 함수 프로그래머 (이름, 나이, 제목) {} 프로그래머 .protoplem = object.create (person.protople); // 상속 관계 프로그래머 생성 프로그래머 .prototype.constructor = 프로그래머; // 생성자의 포인팅을 수정합니다부모 수업 메소드를 호출하십시오
기능인 (이름, 나이) {this.name = 이름; this.age = age;} person.prototype.headcount = 1; person.prototype.eat = function () {console.log ( 'Eating ...');} 함수 프로그래머 (이름, 연령, 제목) {person.apply (this, Arguments); // 부모 클래스의 생성자를 호출} 프로그래머 .prototype = object.create (person.prototyp); propermer.prototype.constructor = 프로그래머; 프로그래머.prototype.languge = "js"; programmer.prototype.work = function () {console.log ( ''+ this.language에서 작동합니다. person.prototype.eat.Apply (이, 인수); // 부모 클래스에서 메소드를 호출}패키지
네임 스페이스
JS에는 네임 스페이스가 없으므로 객체로 시뮬레이션 할 수 있습니다.
var app = {}; // 네임 스페이스 앱 // 모듈 1App.Module1 = {이름 : 'AllIn', f : function () {console.log ( 'hi Robot'); }}; app.Module1.name; // "Allin"app.Module1.f (); // 안녕하세요 로봇정적 멤버
기능인 (이름) {var age = 100; this.name = name;} // static member person.walk = function () {console.log ( 'static');}; person.walk (); // 정적개인 및 대중
기능인 (id) {// 개인 속성 및 메소드 var name = 'Allin'; var work = function () {console.log (this.id); }; // 공개 속성 및 방법 is.id = id; this.say = function () {console.log ( 'say hello'); work.call (this); };}; var p1 = 새로운 사람 (123); p1.name; // undefinedp1.id; // 123p1.say (); // 안녕하세요 123모듈 식
var modulea; modulea = function () {var prop = 1; function func () {} return {func : func, prop};} (); // 즉시 익명 함수를 실행합니다소품, func는 글로벌 범위로 유출되지 않습니다. 또는 다른 글쓰기 방법, 새로 사용하십시오
modulea = new function () {var prop = 1; function func () {} this.func = func; this.prop = prop;}다형성
시뮬레이션 방법 다시로드
인수 속성은 함수 호출의 실제 매개 변수 수를 얻을 수 있으며이를 사용하여 메소드의 과부하를 시뮬레이션 할 수 있습니다.
함수 데모 (a, b) {console.log (demo.length); // 공식 매개 변수 수를 가져옵니다. console.log (arguments.length); // 실제 매개 변수 수를 가져옵니다. console.log (Arguments [0]); // 첫 번째 실제 매개 변수 4 console.log (인수 [1]); // 두 번째 실제 매개 변수 5} 데모 (4, 5, 6); // 변수 길이의 추가 구현 실제 매개 변수 함수 add () {var total = 0; for (var i = arguments.length.length-1; i> = 0; i-) {Total += arguments [i]; } return total;} console.log (add (1)); // 변수 길이의 추가 구현 실제 매개 변수 함수 add () {var total = 0; for (var i = arguments.length.length-1; i> = 0; i-) {Total += arguments [i]; } return total;} console.log (add (1)); // 1console.log (add (1, 2, 3)); // 7 // 다른 매개 변수의 경우 funtsize () {var ele = document.getElementById ( 'js'); if (arguments.length == 0) {return ele.style.fontsize; } else {ele.style.fontsize = 인수 [0]; }} fontsize (18); console.log (fontsize ()); // 다른 유형의 경우 function setting () {var ele = document.getElementById ( 'js'); if (typeof arguments [0] === "object") {for (var p in arguments [0]) {ele.style [p] = arguments [0] [p]; }} else {ele.style.fontsize = 인수 [0]; ele.style.backgroundColor = 인수 [1]; }} 설정 (18, '빨간색'); 설정 ({fontsize : 20, backgroundColor : 'Green'});방법을 다시 작성하십시오
함수 f () {} var f = new f (); f.prototype.run = function () {console.log ( 'f');} f.run (); // ff.run = function () {console.log ( 'fff');} f.run (); // fff초록 수업
새로운 오류를 던지십시오 ( ''); 생성자에서는 예외를 던집니다. 이것은이 클래스가 직접 호출되는 것을 방지합니다.
function detectorbase () {새 오류 ( '추상 클래스는 직접 호출 할 수 없습니다!');} detectorbase.protopty.detect = function () {console.log ( 'Detection Starting ...');}; detectorbase.prototype.stop = function () {console.log ( 'detection suped (') error ( 'error');}; // var d = new detectorbase (); // uppect 오류 : 초록 클래스를 직접 호출 할 수 없습니다! function linkdetector () {} linkdetector.prototype = object.create (detectorbase.creatople); linkdetector.prototype.constructor = linkdetector; new linkdetector (); // linkDetector {} __ proto__ : linkdetectorl.detect (); // 감지 시작 ... l.init (); // 끊임없는 오류 : 오류