码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript Patterns 3.2 Custom Constructor Functions

时间:2014-05-30 00:14:49      阅读:308      评论:0      收藏:0      [点我收藏+]

标签:des   c   style   class   blog   code   

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).

bubuko.com,布布扣
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" 
bubuko.com,布布扣

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.

bubuko.com,布布扣
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"   
bubuko.com,布布扣

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.

JavaScript Patterns 3.2 Custom Constructor Functions,布布扣,bubuko.com

JavaScript Patterns 3.2 Custom Constructor Functions

标签:des   c   style   class   blog   code   

原文地址:http://www.cnblogs.com/haokaibo/p/Custom-Constructor-Functions.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!