객체 지향 프로그래밍(OOP)이란 무엇입니까? 객체지향 프로그래밍의 특징
객체 지향 프로그래밍(OOP)이란 무엇인가요? 객체 사고를 바탕으로 코드를 작성하는 것이 객체 지향 프로그래밍입니다.
객체 지향 프로그래밍의 특징
추상: 핵심 문제 포착
캡슐화: 메소드는 객체를 통해서만 액세스할 수 있습니다.
상속: 기존 개체에서 상속 새로운 객체
다형성: 여러 객체의 다양한 형태
객체 구성
속성: 객체 아래의 변수를 객체의 속성이라고 합니다
메소드 : 객체 아래의 함수를 객체 메소드라고 합니다
var arr = []; arr.number = 10; //对象下面的变量:叫做对象的属性//alert( arr.number );//alert( arr.length );arr.test = function(){ //对象下面的函数 : 叫做对象的方法alert(123); }; arr.test();//方法arr.push();//方法arr.sort();
객체 생성
var obj=new Object();//创建一个空的对象obj.name='小明'; //属性obj.showName=function(){ //方法alert(this.name);//this指向obj } obj.showName();//小明
두 개 이상의 객체를 생성해야 하는 경우
var obj1=new Object();//创建一个空的对象obj1.name='小明'; //属性obj1.showName=function(){ //方法alert(this.name);//this指向obj } obj1.showName();//小明var obj2=new Object();//创建一个空的对象obj2.name='小灰'; //属性obj2.showName=function(){ //方法alert(this.name);//this指向obj } obj2.showName();//小灰
다음을 사용하세요. 객체 함수나 객체 리터럴을 사용하면 객체 지향 객체를 생성할 수 있지만 여러 객체를 생성해야 하는 경우 대량의 중복 코드가 생성됩니다. 이 문제는 팩토리 메소드를 통해 해결할 수 있습니다.
Factory 메소드 ---- ------ ----------객체 지향의 캡슐화 기능
//工厂方式 : 封装函数function createPerson(name){var obj = new Object(); obj.name = name; obj.showName = function(){ alert( this.name ); };return obj; }var p1 = createPerson('小明'); p1.showName();var p2 = createPerson('小强'); p2.showName();
객체 유형을 인식할 수 없습니다
생성자 패턴 --------------------------객체에 메소드 추가
//new 后面调用的函数叫构造函数function CreatePerson(name){this.name=name;this.showName=function(){ alert(this.name); } }var p1=new CreatePerson('小明');//当new去调用一个函数时,函数中的this就是创建出来的对象而函数中的返回值就是this p1.showName();var p2=new CreatePerson('小强'); p2.showName();
- 객체를 명시적으로 생성하지 않습니다.
- 이 개체에 속성과 메서드를 직접 할당합니다.
- 반환 문이 없습니다
생성자는 위 팩토리 메서드의 문제를 해결하지만 단점도 있습니다. 즉, 개체를 생성할 때 각 개체에는 고유한 메서드 집합이 있습니다.
정의된 각 함수는 개체를 인스턴스화합니다.
예: 테스트 예제의
function CreatePerson(name){ this.name = name;this.showName = function(){ alert( this.name ); }; }var p1 = new CreatePerson('小明');//p1.showName();var p2 = new CreatePerson('小强');//p2.showName();alert( p1.showName == p2.showName ); //false 它们的值相同,地址不同
对比上面的几个例子,不难看出基本类型和对象类型的区别了,对象类型的赋值不仅是值的复制,也是引用的传递;提到了对象的引用应该很清楚上述p1.showName==p2.showName为何会返回结果是false
原型模式(prototype) -------------------- 给一类对象添加方法
原型(prototype):重写对象下面公用的属性或方法,让公用的属性或方法在内存中只存在一份(提高性能),也就是说所有在原型对象中创建的属性或方法都直接被所有对象实例共享。
原型:类比css中的class
普通方法:类比css中的style
var arr = [1,2,3,4,5];var arr2 = [2,2,2,2,2]; Array.prototype.sum = function(){//原型prototype : 要写在构造函数的下面var result = 0;for(var i=0;i<this.length;i++){ result += this[i]; }return result; }; alert( arr.sum() ); //15alert( arr2.sum() ); //10
原型优先级:如果在实例中添加了一个属性,而该属性与实例原型中的一个属性同名,该属性将会屏蔽原型中的那个属性
例子1:
var arr = []; arr.number = 10; Array.prototype.number = 20; alert(arr.number);//10
例子2:
Array.prototype.a=12;//原型属性var arr=[1,2,3]; alert(arr.a);//12arr.a=5;//实例属性alert(arr.a);//5
工厂方式之原型
function CreatePerson(name){//普通方法this.name=name; } CreatePerson.prototype.showName=function(){//原型alert(this.name); }var p1=new CreatePerson('小明'); p1.showName();var p2=new CreatePerson('小强'); p2.showName(); alert( p1.showName== p2.showName);//true
由上述例子中:p1.showName== p2.showName弹出的结果是true,可见原型解决了构造函数中“每定义一个函数都实例化了一个对象”的问题
原型的运用
选项卡实例:
<!DOCTYPE html><html><head lang="en"><meta charset="UTF-8"><title>选项卡</title><style>#div1 div{width:400px;height:300px;border:1px solid #ccc;overflow: hidden;display: none;margin: 15px 0;}#div1 input{color: #fff;width:100px;height:40px;background: darkseagreen;border:none;font-size: 14px;letter-spacing: 5px;}#div1 p{font-size: 20px;line-height: 24px;text-align: center;color:darkgreen;}#div1 .title{padding: 0;font-weight: bold;}#div1 .active{background:sandybrown;color:#fff;}</style><script>window.onload=function(){var oDiv=document.getElementById('div1');var aInput=oDiv.getElementsByTagName('input');var aDiv=oDiv.getElementsByTagName('div');var i=0;for(i=0;i<aInput.length;i++){ aInput[i].index=i; aInput[i].onmousemove=function(){for(var i=0;i<aInput.length;i++){ aInput[i].className=''; aDiv[i].style.display='none'; } aInput[this.index].className='active'; aDiv[this.index].style.display='block'; } } }</script></head><body><div id="div1"><input class="active" type="button" value="五言律诗"><input type="button" value="七言律诗"><input type="button" value="五言绝句"><input type="button" value="七言绝句"><div style="display: block;"><p class="title">落 花</p><p class="author">李商隐</p><p>高阁客竟去,小园花乱飞。</p><p>参差连曲陌,迢递送斜晖。</p><p>肠断未忍扫,眼穿仍欲归。</p><p>芳心向春尽,所得是沾衣。</p></div><div><p class="title">蜀 相</p><p class="author">杜甫</p><p>丞相祠堂何处寻,锦官城外柏森森。</p><p>映阶碧草自春色,隔叶黄鹂空好音。</p><p>三顾频烦天下计,两朝开济老臣心。</p><p>出师未捷身先死,长使英雄泪满襟。</p></div><div><p class="title">八阵图</p><p class="author">杜甫</p><p>功盖三分国,名成八阵图。</p><p>江流石不转,遗恨失吞吴。</p></div><div><p class="title">泊秦淮</p><p class="author">杜牧</p><p>烟笼寒水月笼沙,夜泊秦淮近酒家。</p><p>商女不知亡国恨,隔江犹唱后庭花。</p></div></div></body></html>
效果(鼠标经过按钮时选项卡切换):
面向对象选项卡:
<!DOCTYPE html><html><head lang="en"><meta charset="UTF-8"><title>选项卡</title><style>#div1 div,#div2 div{width:400px;height:300px;border:1px solid #ccc;overflow: hidden;display: none;margin: 15px 0;}#div1 input,#div2 input{color: #fff;width:100px;height:40px;background: darkseagreen;border:none;font-size: 14px;letter-spacing: 5px;}#div1 p,#div2 p{font-size: 20px;line-height: 24px;text-align: center;color:darkgreen;}#div1 .title,#div2 .title{padding: 0;font-weight: bold;}#div1 .active,#div2 .active{background:sandybrown;color:#fff;}</style><script>window.onload=function(){var t1=new TabSwitch('div1'); t1.switch(); var t2=new TabSwitch('div2');//面向对象的复用性 t2.switch(); t2.autoPlay();/*alert(t2.switch==t1.switch);//ture*/}function TabSwitch(id){this.oDiv=document.getElementById(id);this.aInput=this.oDiv.getElementsByTagName('input');this.aDiv=this.oDiv.getElementsByTagName('div');this.iNow=0;//自定义属性} TabSwitch.prototype.switch=function(){//原型for(var i=0;i<this.aInput.length;i++){var This=this;//将指向面向对象的this保存下来this.aInput[i].index=i;this.aInput[i].onmousemove=function(){ This.tab(this);//This指向面向对象 this指向this.aInput[i] } } } TabSwitch.prototype.tab=function(obj){//原型for(var i=0;i<this.aInput.length;i++){this.aInput[i].className='';this.aDiv[i].style.display='none'; }this.aInput[obj.index].className='active';this.aDiv[obj.index].style.display='block'; }//自动播放 TabSwitch.prototype.autoPlay=function(){var This=this; setInterval(function(){if(This.iNow==This.aInput.length-1){ This.iNow=0; }else{ This.iNow++; }for(var i=0;i<This.aInput.length;i++){ This.aInput[i].className=''; This.aDiv[i].style.display='none'; } This.aInput[This.iNow].className='active'; This.aDiv[This.iNow].style.display='block'; },1000); }</script></head><body><div id="div1"><input class="active" type="button" value="五言律诗"><input type="button" value="七言律诗"><input type="button" value="五言绝句"><input type="button" value="七言绝句"><div style="display: block;"><p class="title">落 花</p><p class="author">李商隐</p><p>高阁客竟去,小园花乱飞。</p><p>参差连曲陌,迢递送斜晖。</p><p>肠断未忍扫,眼穿仍欲归。</p><p>芳心向春尽,所得是沾衣。</p></div><div><p class="title">蜀 相</p><p class="author">杜甫</p><p>丞相祠堂何处寻,锦官城外柏森森。</p><p>映阶碧草自春色,隔叶黄鹂空好音。</p><p>三顾频烦天下计,两朝开济老臣心。</p><p>出师未捷身先死,长使英雄泪满襟。</p></div><div><p class="title">八阵图</p><p class="author">杜甫</p><p>功盖三分国,名成八阵图。</p><p>江流石不转,遗恨失吞吴。</p></div><div><p class="title">泊秦淮</p><p class="author">杜牧</p><p>烟笼寒水月笼沙,夜泊秦淮近酒家。</p><p>商女不知亡国恨,隔江犹唱后庭花。</p></div></div><div id="div2"><input class="active" type="button" value="五言律诗"><input type="button" value="七言律诗"><input type="button" value="五言绝句"><input type="button" value="七言绝句"><div style="display: block;"><p class="title">落 花</p><p class="author">李商隐</p><p>高阁客竟去,小园花乱飞。</p><p>参差连曲陌,迢递送斜晖。</p><p>肠断未忍扫,眼穿仍欲归。</p><p>芳心向春尽,所得是沾衣。</p></div><div><p class="title">蜀 相</p><p class="author">杜甫</p><p>丞相祠堂何处寻,锦官城外柏森森。</p><p>映阶碧草自春色,隔叶黄鹂空好音。</p><p>三顾频烦天下计,两朝开济老臣心。</p><p>出师未捷身先死,长使英雄泪满襟。</p></div><div><p class="title">八阵图</p><p class="author">杜甫</p><p>功盖三分国,名成八阵图。</p><p>江流石不转,遗恨失吞吴。</p></div><div><p class="title">泊秦淮</p><p class="author">杜牧</p><p>烟笼寒水月笼沙,夜泊秦淮近酒家。</p><p>商女不知亡国恨,隔江犹唱后庭花。</p></div></div></body></html>
效果(第二个选项卡加了一个自动切换功能):
面向对象中this的问题
一般会出现问题的情况有两种:
定时器
事件
例子1:
//定时器function Aaa(){ var _this=this;//将当前this值保存this.a=12; setInterval(function(){//定时器中this指向window _this.show(); },1000); } Aaa.prototype.show=function(){ alert(this.a); }var obj=new Aaa();//12
例子2:
<!DOCTYPE html><html><head lang="en"><meta charset="UTF-8"><title>面向对象中this的问题-----事件</title><script>function Bbb(){var _this=this;this.b=5; document.getElementById('btn1').onclick=function(){//点击事件 _this.show(); }}
Bbb.prototype.show=function(){ alert(this.b); } window.onload=function(){var p2=new Bbb(); }</script></head><body><input id="btn1" type="button" value="按钮"></body></html>
上面两个是分别对定时器和事件中this问题的解决方法,即将指向对象的this保存到了_this中,在嵌套函数中调用对象的方法或属性时用 _this.属性 或 _this.方法
再来个实例:
拖拽效果:
<!DOCTYPE html><html><head lang="en"><meta charset="UTF-8"><title>最初写的拖拽效果</title> <style> #div1{ width:100px; height:100px; background: red; position: absolute; } </style><script>window.onload=function(){var oDiv=document.getElementById('div1'); oDiv.onmousedown=function(ev){var oEvent=ev||event;var disX=0;var disY=0;var disX=oEvent.clientX-oDiv.offsetLeft;var disY=oEvent.clientY-oDiv.offsetTop; document.onmousemove=function(ev){var oEvent=ev||event; oDiv.style.left=oEvent.clientX-disX+'px'; oDiv.style.top=oEvent.clientY-disY+'px'; }; document.onmouseup=function(){ document.onmousemove=null; document.onmouseup=null; };return false; } }</script></head><body><div id="div1"></div></body></html>
面向对象的拖拽
<!DOCTYPE html><html><head lang="en"><meta charset="UTF-8"><title>面向对象写的拖拽效果</title><style>#div1{width:100px;height:100px;background: red;position: absolute;}</style><script>window.onload=function(){var p=new Darg('div1'); p.init(); }function Darg(id){this.oDiv=document.getElementById(id); //属性this.disX=0;//属性this.disY=0;//属性} Darg.prototype.init=function(){//原型 方法var This=this;this.oDiv.onmousedown=function(ev){var oEvent=ev||event; This.fnDown(oEvent);return false; } } Darg.prototype.fnDown=function(ev){//原型 方法var This=this;this.disX=ev.clientX-this.oDiv.offsetLeft;this.disY=ev.clientY-this.oDiv.offsetTop; document.onmousemove=function(ev){var oEvent=ev||event; This.fnMove(oEvent); }; document.onmouseup=function(){ This.fnUp(); }; } Darg.prototype.fnMove=function(ev){//原型this.oDiv.style.left=ev.clientX-this.disX+'px';this.oDiv.style.top=ev.clientY-this.disY+'px'; } Darg.prototype.fnUp=function(){//原型 document.onmousemove=null; document.onmouseup=null; }</script></head><body><div id="div1"></div></body></html>
위 내용은 객체 지향 프로그래밍(OOP)이란 무엇입니까? 객체지향 프로그래밍의 특징의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











정규식을 사용하여 PHP 배열에서 중복 값을 제거하는 방법: 정규식 /(.*)(.+)/i를 사용하여 중복 항목을 일치시키고 바꿉니다. 배열 요소를 반복하고 preg_match를 사용하여 일치하는지 확인합니다. 일치하면 값을 건너뛰고, 그렇지 않으면 중복 값이 없는 새 배열에 추가합니다.

MySQL 쿼리 결과 배열을 객체로 변환하는 방법은 다음과 같습니다. 빈 객체 배열을 만듭니다. 결과 배열을 반복하고 각 행에 대해 새 개체를 만듭니다. foreach 루프를 사용하여 각 행의 키-값 쌍을 새 개체의 해당 속성에 할당합니다. 개체 배열에 새 개체를 추가합니다. 데이터베이스 연결을 닫습니다.

PHP에서 배열은 순서가 지정된 시퀀스이며 요소는 인덱스로 액세스됩니다. 객체는 new 키워드를 통해 생성된 속성과 메서드가 있는 엔터티입니다. 배열 액세스는 인덱스를 통해 이루어지며, 객체 액세스는 속성/메서드를 통해 이루어집니다. 배열 값이 전달되고 객체 참조가 전달됩니다.

C++에서는 함수가 객체를 반환할 때 주의해야 할 세 가지 사항이 있습니다. 객체의 수명 주기는 메모리 누수를 방지하기 위해 호출자가 관리합니다. 매달린 포인터를 피하고 메모리를 동적으로 할당하거나 개체 자체를 반환하여 함수가 반환된 후에도 개체가 유효한지 확인하세요. 컴파일러는 성능을 향상시키기 위해 반환된 개체의 복사 생성을 최적화할 수 있지만 개체가 값 의미 체계에 따라 전달되는 경우 복사 생성이 필요하지 않습니다.

PHP 함수는 return 문과 객체 인스턴스를 사용하여 객체를 반환함으로써 데이터를 사용자 정의 구조로 캡슐화할 수 있습니다. 구문: functionget_object():object{}. 이를 통해 사용자 정의 속성과 메소드를 사용하여 객체를 생성하고 객체 형태로 데이터를 처리할 수 있습니다.

1. 프로그래밍은 웹사이트, 모바일 애플리케이션, 게임, 데이터 분석 도구 등 다양한 소프트웨어와 애플리케이션을 개발하는 데 사용될 수 있습니다. 응용 분야는 매우 광범위하여 과학 연구, 의료, 금융, 교육, 엔터테인먼트 등 거의 모든 산업을 포괄합니다. 2. 프로그래밍을 배우면 문제 해결 능력과 논리적 사고 능력을 향상하는 데 도움이 됩니다. 프로그래밍하는 동안 우리는 문제를 분석 및 이해하고, 해결책을 찾고, 이를 코드로 변환해야 합니다. 이러한 사고방식은 우리의 분석적이고 추상적인 능력을 키우고 실제적인 문제를 해결하는 능력을 향상시킬 수 있습니다.

C++ 프로그래밍 퍼즐은 피보나치 수열, 계승, 해밍 거리, 배열의 최대값과 최소값 등과 같은 알고리즘 및 데이터 구조 개념을 다룹니다. 이러한 퍼즐을 풀면 C++ 지식을 통합하고 알고리즘 이해 및 프로그래밍 기술을 향상시킬 수 있습니다.

Python은 초보자에게 문제 해결 능력을 부여합니다. 사용자 친화적인 구문, 광범위한 라이브러리 및 변수, 조건문 및 루프 사용 효율적인 코드 개발과 같은 기능을 제공합니다. 데이터 관리에서 프로그램 흐름 제어 및 반복 작업 수행에 이르기까지 Python은 제공합니다.
