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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值