zoukankan      html  css  js  c++  java
  • JavaScript Patterns 3.2 Custom Constructor Functions

    When you invoke the constructor function with new, the following happens inside the function:

    • An empty object is created and referenced by this variable, inheriting the prototype of the function.

    • Properties and methods are added to the object referenced by this.

    • The newly created object referenced by this is returned at the end implicitly (if no other object was returned explicitly).

    var Person = function (name) {
    
        this.name = name;
    
        this.say = function () {
    
            return "I am " + this.name;
    
        };
    
    };   
    
    var adam = new Person("Adam");
    
    adam.say(); // "I am Adam" 

    Note

    reusable members, such as methods, should go to the prototype.

    Person.prototype.say = function () {
    
        return "I am " + this.name;
    
    };

    Constructor's Return Values

    When invoked with new, a constructor function always returns an object inheriting from the constructor's prototype.

    var Objectmaker = function () {
    
        // this `name` property will be ignored
    
        // because the constructor
    
        // decides to return another object instead
    
        this.name = "This is it";
    
        // creating and returning a new object
    
        var that = {};
    
        that.name = "And that's that";
    
        return that;
    
    };
    
    // test
    
    var o = new Objectmaker();
    
    console.log(o.name); // "And that's that"   

    You have the freedom to return any object in your constructors, as long as it's an object. Attempting to return something that's not an object (like a string or a boolean false, for example) will not cause an error but will simply be ignored, and the object referenced by this will be returned instead.

  • 相关阅读:
    如何查看MySQL执行的每条SQL
    最简单的方式在linux上升级node.js版本
    快速理解字符串和编码
    macaca常见错误排查
    macaca自动化初体验
    F2eTest程序快捷方式安装到桌面
    centos下mysqlreport安装和使用
    前端纯css 图片的模糊处理
    gulp入门学习教程(入门学习记录)
    关于nodejs中npm命令没有反应的解决方法
  • 原文地址:https://www.cnblogs.com/haokaibo/p/Custom-Constructor-Functions.html
Copyright © 2011-2022 走看看