JS 객체 지향 사용 예

小云云
풀어 주다: 2018-03-06 14:06:02
원래의
1406명이 탐색했습니다.

객체는 속성과 메서드의 모음입니다. 객체지향이란 무엇인가? 객체지향은 프로그래밍 아이디어이자 개념입니다. js에서는 프로토타입이라는 메소드를 통해 객체지향 프로그래밍을 구현합니다.

<!DOCTYPE html><html><head lang="en">
    <meta charset="UTF-8">
    <title>创建对象</title></head><body><button type="button" onclick="showInfo();">点击显示学生信息</button><script type="text/javascript">
     //创建一个学生对象
     var student=new Object();    //创建对象的属性并且赋值
    student.age=50;
    student.name="小黑";
    student.address="海淀区";    //创建对象的方法
    student.sayHello=function(){
        document.write("姓名:"+student.name+"<br/>");
        document.write("年龄:"+student.age+"<br/>");
        document.write("住址:"+this.address+"<br/>");
    }    //用户点击按钮触发的事件
    function showInfo(){
        student.sayHello(); //调用student的方法
    }    //现在只是创建了一个对象! 如果我们想创建多个 那么代码冗余!</script></body></html>
로그인 후 복사

리터럴을 통해 객체 생성

학생 객체 생성
{속성 1: 값 1, 속성 2: 값 2, 속성 3: 값 3}
​ ​ ​Json 데이터 형식: 데이터 변환 형식입니다
01. 키-값 쌍의 형태입니다
02. 객체는 {}에 저장됩니다
03. 컬렉션은 []
에 저장됩니다. 04. 데이터는 쉼표로 구분하고 속성과 속성값은 콜론으로 구분합니다

<!DOCTYPE html><html><head lang="en">
    <meta charset="UTF-8">
    <title>通过字面量来创建对象</title></head><body>
     <button type="button" onclick="showInfo();">点击显示学生信息</button><script type="text/javascript">
     var student={
         age:50,
         name:"小黑",
         address:"海淀区",
        sayHello:function(){  //方法
            document.write("姓名:"+this.name+"<br/>");
            document.write("年龄:"+this.age+"<br/>");
            document.write("住址:"+this.address+"<br/>");
        }
     }    // student 我们称之为变量   =右边的{}中的数据,我们称之为 字面量!
     //用户点击按钮触发的事件
     function showInfo(){
         student.sayHello(); //调用student的方法
     }     // 问题依然存在:现在只是创建了一个对象! 如果我们想创建多个 那么代码冗余!</script></body></html>
로그인 후 복사

생성자를 통해 여러 객체 생성

<!DOCTYPE html><html><head lang="en">
    <meta charset="UTF-8">
    <title>通过构造函数创建多个对象</title></head><body><script type="text/javascript">
    //创建构造函数   函数名称首字母必须大写
    function Student(name,age,address){
         //声明属性并赋值
        this.name=name;        this.age=age;        this.address=address;        //设置方法
        this.sayHello=function(){
            document.write("姓名:"+this.name+"<br/>");
            document.write("年龄:"+this.age+"<br/>");
            document.write("住址:"+this.address+"<br/>");
        }
    }    //创建多个对象
    var  stu1=new Student("小黑1",50,"天堂1");    var  stu2=new Student("小黑2",51,"天堂2");    var  stu3=new Student("小黑3",52,"天堂3");  //分别调用对象的方法
    stu1.sayHello();
    stu2.sayHello();
    stu3.sayHello();  // 所有的对象都有一个constructor属性!指向了构造函数!
    document.write("stu1.constructor指向了Student:"+(stu1.constructor==Student)+"<br>");    //instanceof 判断某个对象是否属于某个类型
    document.write("stu1属于Student吗?"+(stu1 instanceof Student)+"<br>");
    document.write("stu1属于Object吗?"+(stu1 instanceof Object)+"<br>");
    document.write("stu1属于Function吗?"+(stu1 instanceof Function)+"<br>");</script></body></html>
로그인 후 복사

프로토타입 객체

참고:
01. 모든 객체에는 생성자 속성이 있습니다! 생성자를 가리킨다!
​ 02. 함수를 생성할 때 해당 함수는 프로토타입 속성을 가지게 되는데,
이 속성은 생성자를 통해 생성된 프로토타입 객체를 가리킵니다! 학생.프로토타입
03. 프로토타입 객체는 다른 객체에 공유된 속성과 메소드를 제공하는 메모리상의 객체입니다!
04.prototype 속성은 함수에만 사용 가능합니다!
​ 05. 각 객체에는 프로토타입 객체를 가리키는 __proto__ 속성이 있습니다! __proto__属性,指向了原型对象!

<!DOCTYPE html><html><head lang="en">
    <meta charset="UTF-8">
    <title>原型对象</title></head><body><script type="text/javascript">
    /*创建一个构造函数*/
    function  Student(){}   //通过原型对象来创建对象
    Student.prototype.name;
    Student.prototype.age;
    Student.prototype.address;
    Student.prototype.sayHello=function(){
        document.write("姓名:"+this.name+"<br/>");
        document.write("年龄:"+this.age+"<br/>");
        document.write("住址:"+this.address+"<br/>");
    }    var  stu1=new Student();
    stu1.name="小白";
    stu1.age=52;
    stu1.address="天上人间";    var  stu2=new Student();
    stu2.sayHello();    // 验证每个对象都有一个__proto__属性,指向了原型对象!
    document.write(stu2.__proto__==Student.prototype);</script></body></html>
로그인 후 복사

01.prototype属性只有函数才有!
02.每个对象都有一个__proto__属性,指向了原型对象!

<!DOCTYPE html><html><head lang="en">
    <meta charset="UTF-8">
    <title>深入原型对象</title></head><body><script type="text/javascript">
    //01.验证只有函数有prototype属性
    var  a={};
    document.write(a.prototype+"<br/>");
    document.write(a.__proto__+"<br/>");    var b=function(){}
    document.write(b.prototype+"<br/>");
    document.write(b.__proto__+"<br/>");    var c=new b();    // 02.验证每个对象都有一个__proto__属性,指向了原型对象!
    document.write(c.__proto__== b.prototype);</script></body></html>
로그인 후 복사

原型链

原型链:
01.一个原型对象是另一个原型对象的实例! 小猫是动物的一个实例!
02. 相关的原型链层层递进,就构成了实例和原型对象的链条,我们就称之为原型链!
蹲在角落里的那只黑猫 (实例)
继承了
猫类(01.相当于黑猫来说是原型对象 02.相对于动物来说是一个实例)
继承了
动物类(01.所有动物的原型对象 02.object的实例)
继承了
Object(所有原型对象的顶级)
只要是个对象都有__proto__属性,指向了原型对象!
问题:
Object是对象!
__proto__

<!DOCTYPE html><html><head lang="en">
    <meta charset="UTF-8">
    <title>原型链</title></head><body><script type="text/javascript">
        //模拟一个构造函数
          var   Student=function(){};         var stu1=new Student();
            document.write(stu1.__proto__+"<br/>"); //student
            document.write(stu1.__proto__.__proto__+"<br/>");//function
            document.write(stu1.__proto__.__proto__.__proto__+"<br/>");  //  object null
            document.write("===================================");
          document.write((stu1.__proto__===Object.prototype)+"<br/>");  //false
          document.write((Student.prototype.__proto__===Object.prototype)+"<br/>");  //true</script></body></html>
로그인 후 복사

01. 프로토타입 속성은 함수에만 사용할 수 있습니다!

02. 각 객체에는 프로토타입 객체를 가리키는 __proto__ 속성이 있습니다!

<!DOCTYPE html><html><head lang="en">
    <meta charset="UTF-8">
    <title>借用构造函数的同时传递参数</title></head><body>

   <script type="text/javascript">
         //创建Animal的构造
       function Animal(name){
         this.name=name;
       }       //创建Dog的构造
       function Dog(){
           //借用构造  传递参数
           Animal.call(this,"小黑狗");           this.age=50;
       }       //创建Cat的构造
       function Cat(){
           //借用构造
           Animal.call(this,"小猫咪");           this.health=100;
       }         //创建小狗的实例
       var dog1=new Dog();
       document.write(dog1.name);
       document.write(dog1.age);         //创建小猫咪的实例
       var cat1=new Cat();
       document.write(cat1.name);
       document.write(cat1.health);   </script></body></html>
로그인 후 복사

프로토타입 체인


프로토타입 체인:
01. 프로토타입 객체는 또 다른 프로토타입 객체의 인스턴스입니다! 새끼 고양이는 동물의 예입니다!
02. 관련 프로토타입 체인이 레이어별로 진행되어 인스턴스와 프로토타입 객체의 체인을 형성합니다.

구석에 쪼그리고 앉아 있는 검은 고양이(예시)
>            상속됨

고양이 클래스 (01. 검은 고양이에 해당하며 프로토타입 객체입니다. 02. 동물에 비하면 인스턴스입니다.)
>            상속됨 동물 클래스 (01. 모든 동물의 프로토타입 객체 02. 객체의 인스턴스) > 객체(모든 프로토타입 객체의 최상위 수준)

객체인 한 프로토타입 객체를 가리키는 __proto__ 속성이 있습니다!

질문: ​ ​ ​ 객체는 객체다! __proto__ 속성이 있습니다!

속성 값이 null입니다!

빌린 생성자rrreee🎜결합 상속🎜🎜🎜결합 상속: 🎜 때로는 의사고전적 상속이라고도 하며 프로토타입 연결 및 생성자 차용 기술을 결합합니다. 🎜 두 세계의 장점을 모두 활용하는 상속 패턴은 프로토타입 체인을 사용하여 프로토타입 속성과 메서드를 상속합니다. 인스턴스 속성 상속은 생성자를 빌려서 달성됩니다🎜🎜rrreee🎜관련 권장 사항: 🎜🎜js 객체 지향 상속 지식 자세한 설명🎜🎜🎜🎜JS 객체 지향 프로그래밍 세부 지침🎜🎜🎜🎜JavaScript 객체 지향 디자인_js-지향 객체 🎜🎜

위 내용은 JS 객체 지향 사용 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!