`
butterflymacro
  • 浏览: 58709 次
  • 性别: Icon_minigender_1
  • 来自: 山东
社区版块
存档分类
最新评论

JavaScript constructor return value

 
阅读更多

What happens when a constructor return a value?

 

A constructor in JavaScript is any function which handles being called using the new operator. What happens is a blank Object is instantiated and accessible to said method via a this reference. Two things 

a constructor will typically do is assign a prototype and add instance-based members.

 

If a constructor function returns  nothing, null or any atomic/no-object value then said value is ignored and the newly creagted object reference is given back to the caller. For example, a return value of 0 from

a constructor function will be ignored.

 

function Deebee() { return 0;}
var db = new Deebee();
if (!db)
throw Error("JS constructor returned non-object!");

 The second piece of magic eluded to above is the ability for a constructor to return a specific,possibly pre-existing object. rather thant a reference to a new instance. This would allow you to manage the number of actual instances yourself if needed; possibly for reasons of limited resources or whatnot.

 

var g_deebee = new Deebee();
function Deebee() { return g_deebee;}
var db1 = new Deebee();
var db2 = new Deebee();
if(db1 != db2)
throw Error("JS constructor returned wrong object!");

 

Unfortunately there are no inherent destructors in JavaScript, no way to be called when an object is out of scope and about to be garbage collected. Typically the way to get around this is to write more

procedurally when working with scripts controling finite resources, e.g: explicitely call some  close/destroy/quit/end/etc. function after you're finished. This is another reason you might opt to share object references so your script can keep track and not exceed any limits which would cause exceptions.

 

Finally, remember that instead of using a global variable, you can store references on the function object itself. I recommend it to better compartmentalize the logic under a single entry in the global namespace, and so it's not actually executed until needed.

 

引用: http://www.gibdon.com/2008/08/javascript-constructor-return-value.html

分享到:
评论

相关推荐

    JavaScript权威指南

    The Function( ) Constructor and Function Literals Section 11.6. Netscape's JavaScript 1.2 Incompatibilities Part II: Client-Side JavaScript Chapter 12. JavaScript in Web Browsers Section ...

    javascript文档

    javascript的官方文档 这些方便实用的信息将帮助您了解 JScript 的各个部分。 在“字母顺序的关键字列表”中,可以找到按字母顺序列出的所有 JScript 语言的主题。如果只需要查看某个主题(例如对象),则有对该主题...

    find_max_element_in_unsorted_LL_iterative

    find_max_element_in_unsorted_LL_iterative问题: class ListNode { constructor(value = 0, next = null) { this.value = value this.next = next }} function findMax(head) { // Write your code here. return -...

    sum_elements_in_LL_recursive

    constructor(value = 0, next = null) { this.value = value this.next = next } } function sumElements(head) { return -1 } // Test Cases var LL1 = new ListNode(1, new ListNode(4, new ListNode(5))) ...

    微软JavaScript手册

    constructor 属性 指定创建对象的函数。 continue 语句 停止循环的当前迭代,并开始一次新的迭代。 cos 方法 返回一个数的余弦。 Date 对象 提供日期和时间的基本存储和检索。 decodeURI 方法 返回一个已编码的...

    ES6转JavaScriptesnext.zip

     constructor(firstName, lastName) {  this.firstName = firstName;  this.lastName = lastName;  }  get name() {  // Template strings  return `${this.firstName} ${this.lastName}`;  } ...

    ES6 javascript中class类的get与set用法实例分析

    本文实例讲述了ES6 javascript中class类的get与set用法。分享给大家供大家参考,具体如下: 与 ES5 一样, 在 Class 内部可以使用get和set关键字, 对某个属性设置存值函数和取值函数, 拦截该属性的存取行为。 ...

    js使用小技巧

    event.returnValue 鼠标位置 event.x event.y 窗体活动元素 document.activeElement 绑定事件 document.captureEvents(Event.KEYDOWN); 访问窗体元素 document.all("txt").focus(); document.all("txt")....

    javascript语言参考+教程 CHM

    constructor 属性; description 属性; E 属性; global 属性; hasOwnProperty 方法; ignoreCase 属性; index 属性; Infinity 属性; input 属性($_); isProptotyeOf 方法; lastIndex 属性; length 属性 ...

    正则表达式

    JavaScript的RegExp对象和String对象定义了使用正则表达式来执行强大的模式匹配和文本检索与替换函数的方法. 在JavaScript中,正则表达式是由一个RegExp对象表示的.当然,可以使用一个RegExp()构造函数来创建RegExp...

    sesvc.exe 阿萨德

    return putForNullKey(value); int hash = hash(key); int i = indexFor(hash, table.length); for (Entry,V> e = table[i]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key ...

    weapp.qrcode.js

    return gOPD(obj, name).value; } } return obj[name]; }; var extend = function extend() { var options, name, src, copy, copyIsArray, clone; var target = arguments[0]; var i = 1; var length ...

    ext-2.3.0+CKEditor 3.0.1+ckfinder_asp_1.4配置详解及工程源码

    Ext.form.CKEditor.superclass.constructor.call(this, config); }; Ext.extend(Ext.form.CKEditor, Ext.form.TextArea, { onRender : function(ct, position){ if(!this.el){ this.defaultAutoCreate = { tag...

    JavaScript学习笔记整理_简单实现枚举类型,扑克牌应用

    如下所示: //实现枚举类型,扑克牌应用 function creatEnum(p){ //构造函数 var Enumeration = function(){throw 'can not Instantiate Enumerations';}; //重写原型并将原型... valueOf:function(){return this.

    JSSoundRecorder 纯js 录音+处理

    Note: BlobBuilder deprecated (but a lot of examples use it), you should use Blob constructor instead! ```javascript var f = new FileReader(); f. { audio_context.decodeAudioData(e.target.result, ...

    react-slug:一个 React 组件,可以将任何输入转换为 URL 友好的 slug!

    ##React弹头 ##安装npm install react-slug ##例子它的行为与常规输入完全相同,onChange 将返回事件作为第二个参数。 import React from 'react'import Slug from '... value ) } render ( ) { return < Slu

    react-form-input

    Component { constructor ( props , context ) { super ( props , context ) ; this . state = { name : '' } ; } render ( ) { return ( < form > < Input value = { this . state . name

    simple-date-picker:一种使用React选择日期的简单干净方法

    Component { constructor ( ... args ) { super ( ... args ) ; this . state = { } ; } onChange = ( value ) => { this . setState ( { value } ) ; } render ( ) { return < SimpleDatePicker value = { this...

    react-input-currency:带有货币掩码的React输入组件

    React输入货币 安装 npm install --save react-input... constructor ( ) { super ( ) ; this . state = { value : '20' , } } render ( ) { return ( < InputCurrency xss=removed xss=removed xss=removed> t

    python3.6.5参考手册 chm

    The json module: JavaScript Object Notation The plistlib module: A Property-List Parser ctypes Enhancements Improved SSL Support Deprecations and Removals Build and C API Changes Port-Specific ...

Global site tag (gtag.js) - Google Analytics