JS 객체지향에 대한 자세한 소개(2)

零下一度
풀어 주다: 2017-06-29 13:37:50
원래의
1027명이 탐색했습니다.

메뉴 탐색, "JS 객체 지향 노트 1", 참고 도서: Ruan Yifeng의 "JavaScript Standard Reference Tutorial"

1. 생성자 및 새 명령

2. 이 키워드

3. 구성 함수 및 새 명령

4. 생성자 및 새 명령

5. 생성자 및 새 명령

6. 생성자 및 새 명령

7. 생성자 및 새 명령

8. 생성자 및 new command

1. 생성자와 new 명령어

1. 생성자

  • JavaScript 언어의 객체 시스템은 "클래스"가 아닌 생성 함수(생성자)와 프로토타입 체인(프로토타입)을 기반으로 합니다. )

  • 일반 함수와 구별하기 위해 생성자 이름의 첫 글자는 일반적으로 대문자로 표시됩니다. 예: var Person = function(){ this.name = 'Wang Dachui' }

  • Features 생성자:
    a. this 키워드는 생성할 객체 인스턴스를 나타내는 함수 본문 내에서 사용됩니다. this关键字,代表了所要生成的对象实例;
       b、生成对象的时候,必需用new命令调用此构造函数

2、new 

  作用:就是执行构造函数,返回一个实例对象 

var Person = function(name, age){this.name = name;this.age = age;this.email = 'cnblogs@sina.com';this.eat = function(){
        console.log(this.name + ' is eating noodles');
    }
}var per = new Person('王大锤', 18);
console.log(per.name + ', ' + per.age + ', ' + per.email); //王大锤, 18, cnblogs@sina.comper.eat();  //王大锤 is eating noodles
로그인 후 복사

执行new命令时的原理步骤:

  1. 创建一个空对象,作为将要返回的对象实例

  2. 将这个空对象的原型,指向构造函数的prototype属性

  3. 将这个空对象赋值给函数内部的this b. new 명령

  4. 2.new

      기능: 생성자를 실행하고 인스턴스 객체를 반환합니다
console.log('---- 返回字符串 start ----');var Person = function(){this.name = '王大锤';return '罗小虎';
}var per = new Person();for (var item in per){
    console.log( item + ': ' + per[item] );
}//---- 返回字符串 start ----//name: 王大锤console.log('----- 返回对象 start ----');var PersonTwo = function(){this.name = '倚天剑';return {nickname: '屠龙刀', price: 9999 };
}var per2 = new PersonTwo();for (var item in per2){
    console.log(item + ': ' + per2[item]);
}//----- 返回对象 start ----//nickname: 屠龙刀//price: 9999
로그인 후 복사


새 명령을 실행할 때의 원칙 단계:

    반환할 객체 인스턴스로 빈 객체를 생성합니다.
    이 빈 객체의 프로토타입을 prototype 속성

    이 빈 객체를 함수

    내의 this 키워드에 할당하세요.

    Start 생성자 내부의 코드를 실행합니다.

    참고: 생성자에 return 키워드가 있는 경우 반환이 객체가 아닌 경우 새 명령은 반환된 정보를 무시하고 최종 반환은 this가 됩니다. 반환 반환이 이와 관련이 없는 새 개체인 경우 최종 new 명령은 이 개체 대신 새 개체를 반환합니다. 샘플 코드:
    var Person = function(){ 
        console.log( this == window );  //truethis.price = 5188; 
    }var per = Person();
    console.log(price); //5188console.log(per);  //undefinedconsole.log('......_-_'); //......_-_console.log(per.price); //Uncaught TypeError: Cannot read property 'helloPrice' of undefined
    로그인 후 복사

    코드 보기

    생성자를 호출할 때 new 키워드를 사용하는 것을 잊어버린 경우 생성자의 this는 전역 개체 창이 되며 속성도 전역 속성이 됩니다.
    생성자에 의해 할당된 변수는 더 이상 객체가 아니지만 정의되지 않은 변수는 JS에서 정의되지 않은 속성을 추가하는 것을 허용하지 않으므로 정의되지 않은 속성을 호출하면 오류가 보고됩니다. 예:
    🎜🎜🎜🎜
    var Person = function(){ 'use strict';
        console.log( this );  //undefinedthis.price = 5188; //Uncaught TypeError: Cannot set property 'helloPrice' of undefined}var per = Person();
    로그인 후 복사
    🎜🎜코드 보기🎜🎜🎜새 키워드를 잊어버리지 않도록 함수 내부 첫 번째 줄에 'use strict'를 추가하는 해결책이 있습니다.🎜🎜 함수의 사용을 나타냅니다. 엄격 모드에서 함수 내부의 이 함수는 전역 개체 창을 가리킬 수 없으며 기본값은 정의되지 않아 새 🎜🎜🎜🎜🎜
    var Person = function(){ //先判断this是否为Person的实例对象,不是就new一个if (!(this instanceof Person)){return new Person();
        }
        console.log( this );  //Person {}this.price = 5188; 
    }var per = Person(); 
    console.log(per.price); //5188
    로그인 후 복사
    로그인 후 복사
    🎜🎜코드 보기🎜🎜 없이 호출하면 오류가 보고됩니다.

    另外一种解决方式,就是在函数内部手动添加new命令:

    var Person = function(){ //先判断this是否为Person的实例对象,不是就new一个if (!(this instanceof Person)){return new Person();
        }
        console.log( this );  //Person {}this.price = 5188; 
    }var per = Person(); 
    console.log(per.price); //5188
    로그인 후 복사
    로그인 후 복사
    View Code

     

     

    二、this关键字

    var Person = function(){
        console.log('1111'); 
        console.log(this); this.name = '王大锤';this.age = 18;this.run = function(){
            console.log('this is Person的实例对象吗:' + (this instanceof Person) ); 
            console.log(this); 
        }
    }var per = new Person();
    per.run();/* 打印日志:
    1111
    Person {}
    this is Person的实例对象吗:true
    Person {name: "王大锤", age: 18, run: function}*/console.log('---------------');var Employ = {
        email: 'cnblogs@sina.com',
        name: '赵日天',
        eat: function(){
            console.log(this);
        }
    }
    
    console.log(Employ.email + ', ' + Employ.name);
    Employ.eat();/* 打印日志:
    ---------------
    cnblogs@sina.com, 赵日天
    Object {email: "cnblogs@sina.com", name: "赵日天", eat: function}*/
    로그인 후 복사
    View Code

    1、this总是返回一个对象,返回属性或方法当前所在的对象, 如上示例代码

    2、对象的属性可以赋值给另一个对象,即属性所在的当前对象可变化,this的指向可变化

    var A = { 
        name: '王大锤', 
        getInfo: function(){return '姓名:' + this.name;
        } 
    }var B = { name: '赵日天' };
    
    B.getInfo = A.getInfo;
    console.log( B.getInfo() ); //姓名:赵日天//A.getInfo属性赋给B, 于是B.getInfo就表示getInfo方法所在的当前对象是B, 所以这时的this.name就指向B.name
    로그인 후 복사
    View Code

     3、由于this指向的可变化性,在层级比较多的函数中需要注意使用this。一般来说,在多层函数中需要使用this时,设置一个变量来固定this的值,然后在内层函数中这个变量。

    示例1:多层中的this

    //1、多层中的this (错误演示)var o = {
        f1: function(){
            console.log(this); //这个this指的是o对象var f2 = function(){
                console.log(this);
            }();//由于写法是(function(){ })() 格式, 则f2中的this指的是顶层对象window    }
    }
    
    o.f1();/* 打印日志:
    Object {f1: function}
    
    Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}*///2、上面代码的另一种写法(相同效果)var temp = function(){
        console.log(this);
    }var o = {
        f1: function(){
            console.log(this); //这个this指o对象var f2 = temp(); //temp()中的this指向顶层对象window    }
    }
    o.f1(); 
    /* 打印日志
    Object {f1: function}
    
    Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}*///表示上面两种写法是一样的效果,this的错误演示//3、多层中this的正确使用:使用一个变量来固定this对象,然后在内层中调用该变量var o = {
        f1: function(){
            console.log(this); //o对象var that = this;var f2 = function(){
                console.log(that); //这个that指向o对象        }();
        }
    }
    o.f1();/* 打印日志:
    Object {f1: function}
    Object {f1: function}*/
    로그인 후 복사
    View Code

    示例2: 数组遍历中的this

    //1、多层中数组遍历中this的使用 (错误演示)var obj = {
        email: '大锤@sina.com', 
        arr: ['aaa', 'bbb', '333'],
        fun: function(){//第一个this指的是obj对象this.arr.forEach(function(item){//这个this指的是顶层对象window, 由于window没有email变量,则为undefinedconsole.log(this.email + ': ' + item);
            });
        }
    }
    
    obj.fun(); 
    /* 打印结果:
    undefined: aaa
    undefined: bbb
    undefined: 333 *///2、多层中数组遍历中this的使用 (正确演示,第一种写法)var obj = {
        email: '大锤@sina.com', 
        arr: ['aaa', 'bbb', '333'],
        fun: function(){//第一个this指的是obj对象var that = this; //将this用变量固定下来this.arr.forEach(function(item){//这个that指的是对象objconsole.log(that.email + ': ' + item);
            });
        }
    }
    obj.fun(); //调用/* 打印日志:
    大锤@sina.com: aaa
    大锤@sina.com: bbb
    大锤@sina.com: 333 *///3、多层中数组遍历中this正确使用第二种写法:将this作为forEach方法的第二个参数,固定循环中的运行环境var obj = {
        email: '大锤@sina.com', 
        arr: ['aaa', 'bbb', '333'],
        fun: function(){//第一个this指的是obj对象this.arr.forEach(function(item){//这个this从来自参数this, 指向obj对象console.log(this.email + ': ' + item);
            }, this);
        }
    }
    obj.fun(); //调用/* 打印日志:
    大锤@sina.com: aaa
    大锤@sina.com: bbb
    大锤@sina.com: 333 */
    로그인 후 복사
    View Code

     

    4、关于js提供的call、apply、bind方法对this的固定和切换的用法

      1)、function.prototype.call(): 函数实例的call方法,可以指定函数内部this的指向(即函数执行时所在的作用域),然后在所指定的作用域中,调用该函数。
      如果call(args)里面的参数不传,或者为null、undefined、window, 则默认传入全局顶级对象window;
      如果call里面的参数传入自定义对象obj, 则函数内部的this指向自定义对象obj, 在obj作用域中运行该函数

    var obj = {};var f = function(){
        console.log(this);return this;
    }
    
    console.log('....start.....');
    f();
    f.call();
    f.call(null);
    f.call(undefined);
    f.call(window);
    console.log('**** call方法的参数如果为空、null和undefined, 则默认传入全局等级window;如果call方法传入自定义对象obj,则函数f会在对象obj的作用域中运行 ****');
    f.call(obj);
    console.log('.....end.....');/* 打印日志:
    ....start.....
    Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
    Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
    Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
    Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
    Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
    **** call方法的参数如果为空、null和undefined, 则默认传入全局等级window;如果call方法传入自定义对象obj,则函数f会在对象obj的作用域中运行 ****
    Object {}
    .....end.....*/
    로그인 후 복사
    View Code

     

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

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