zoukankan      html  css  js  c++  java
  • 关于构造函数的返回值

    很长一段时间认为, 构造函数显式的返回值是无效的, 最终都会返回this。 今天才发现其实是错误的。

    当构造函数中没有return语句时, 会默认返回this, 但是也可以返回任意的对象, 如果返回值不是对象, 仍然返回this。 不过这样也有后遗症, 实例将不会继承构造函数原型上的任何属性。

    例1:

     function Test() {
         this.name = "this's name";
         var that = {};
         that.name = "that's name";
         return 10;
     }
    
     var test1 = new Test();
     console.log(test1.name);   // this's name

    例2:

     function Test() {
         this.name = "this's name";
         var that = {};
         that.name = "that's name";
         return that;
     }
    
     var test1 = new Test();
     console.log(test1.name);   // that's name

    例3:

     function Test() {
         this.name = "this's name";
         var that = {};
         that.name = "that's name";
         return that;
     }
    
     Test.prototype.say = function() {
         alert("hi");
     }
    
     var test1 = new Test();
     console.log(test1.name);   // that's name
     test1.say();         // error
  • 相关阅读:
    web测试学习大纲
    Python语言编程基础
    python文件IO
    Python 正则表达式
    python官网导航翻译
    python常用库
    python连接数据库
    sublime与python交互
    selenium连接浏览器方式
    sublime中运行python时编码格式问题
  • 原文地址:https://www.cnblogs.com/blackwood/p/3282619.html
Copyright © 2011-2022 走看看