最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

JS面向对象的详细介绍(二)

来源:动视网 责编:小采 时间:2020-11-27 20:17:54
文档

JS面向对象的详细介绍(二)

JS面向对象的详细介绍(二):菜单导航,《JS面向对象笔记一》, 参考书籍:阮一峰之《JavaScript标准参考教程》一、构造函数和new命令二、this关键字三、构造函数和new命令四、构造函数和new命令五、构造函数和new命令六、构造函数和new命令七、构造函数和new命令八、构造函数和new
推荐度:
导读JS面向对象的详细介绍(二):菜单导航,《JS面向对象笔记一》, 参考书籍:阮一峰之《JavaScript标准参考教程》一、构造函数和new命令二、this关键字三、构造函数和new命令四、构造函数和new命令五、构造函数和new命令六、构造函数和new命令七、构造函数和new命令八、构造函数和new
 菜单导航,《JS面向对象笔记一》, 参考书籍:阮一峰之《JavaScript标准参考教程》

一、构造函数和new命令

二、this关键字

三、构造函数和new命令

四、构造函数和new命令

五、构造函数和new命令

六、构造函数和new命令

七、构造函数和new命令

八、构造函数和new命令

一、构造函数和new命令

1、构造函数

  • JavaScript语言的对象体系,不是基于“类”的,而是基于构造函数(constructor)和原型链(prototype)

  • 为了与普通函数区别,构造函数名字的第一个字母通常大写,比如: var Person = function(){ this.name = '王大锤'; }

  • 构造函数的特点:
    a、函数体内部使用了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关键字

    4. 开始执行构造函数内部的代码

    注意点:当构造函数里面有return关键字时,如果返回的是非对象,new命令会忽略返回的信息,最后返回时构造之后的this对象;
      如果return返回的是与this无关的新对象,则最后new命令会返回新对象,而不是this对象。示例代码:

    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
    View Code

    如果调用构造函数的时候,忘记使用new关键字,则构造函数里面的this为全局对象window,属性也会变成全局属性,

    则被构造函数赋值的变量不再是一个对象,而是一个未定义的变量,js不允许给undefined添加属性,所以调用undefined的属性会报错。

    示例:

    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
    View Code

    为了规避忘记new关键字现象,有一种解决方式,就是在函数内部第一行加上 : 'use strict';

    表示函数使用严格模式,函数内部的this不能指向全局对象window, 默认为undefined, 导致不加new调用会报错

    var Person = function(){ 'use strict';
     console.log( this ); //undefinedthis.price = 5188; //Uncaught TypeError: Cannot set property 'helloPrice' of undefined}var per = Person();
    View Code

    另外一种解决方式,就是在函数内部手动添加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面向对象的详细介绍(二)

    JS面向对象的详细介绍(二):菜单导航,《JS面向对象笔记一》, 参考书籍:阮一峰之《JavaScript标准参考教程》一、构造函数和new命令二、this关键字三、构造函数和new命令四、构造函数和new命令五、构造函数和new命令六、构造函数和new命令七、构造函数和new命令八、构造函数和new
    推荐度:
    标签: 介绍 js 对象
    • 热门焦点

    最新推荐

    猜你喜欢

    热门推荐

    专题
    Top