zoukankan      html  css  js  c++  java
  • 构造函数new执行与直接执行的区别

    //创建一个Test构造
    function Test(){
       // new执行与直接执行 this的不同指向
       this.init();
    };
    // this 指向 Test
    Test.prototype.init = function(){
      console.log('this is Test');
    }
    // this 指向 window
    function init(){
      console.log('this is window');
    }
    
    //直接执行
    var t = Test(); // this is window
    var test = new Test(); //this is Test

    另补充一点:
    构造函数返回值的问题
    如果一个函数的返回值是引用类型(数组,对象或者函数)的数据,那么这个函数作为构造函数用new运算符执行构造时,运算的结果将被它的返回值取代,这时候,构造函数体内的this值丢失了,取而代之的是被返回的对象;

    //创建一个Test构造
    function Test(){
       this.a = 10;
       return {}; 
    };
    
    console.log( new Test() ); // Object {}
    
    
    //创建一个Test构造
    function Test(){
       this.a = 10;
       return 1; 
    };
    
    console.log( new Test() ); // Test {a: 10}

     参考网站:http://www.jb51.net/article/47871.htm

  • 相关阅读:
    C#调用C++ ---参数传递
    Retained Mode Versus Immediate Mode
    mind map in latex
    vk example
    基本环境
    [转]ld 和 ld.gold 和 ld.bfd
    [转] c++11 int&& 右值引用
    [转] c++11列表初始化
    [转] c++ const, volatile, mutable用法
    [转] c++11 模板元编程
  • 原文地址:https://www.cnblogs.com/marunzhou/p/5634181.html
Copyright © 2011-2022 走看看