Javascript 属性重载 ala PHP?
我正在尝试找到一种像 PHP 中那样进行属性重载的方法: http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members
即
var myobj = function () {}
myobj.prototype.getProperty = function (propertyName) { console.log('Property Requested: ', propertyName); }
var otherObj = function () {};
myobj.hello; // Property Request: hello
otherObj.hello; // undefined
这可能吗?
I'm trying to find a way to to property overloading like it's done in PHP: http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members
i.e.
var myobj = function () {}
myobj.prototype.getProperty = function (propertyName) { console.log('Property Requested: ', propertyName); }
var otherObj = function () {};
myobj.hello; // Property Request: hello
otherObj.hello; // undefined
Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这种事情只能在 ECMAscript 5 中完成,并非所有浏览器(例如 IE)都支持它。使用
Object.defineProperty
,您可以使用访问器函数创建属性 - 因此您可以在根据对象状态而变化的数组中实现诸如length
之类的属性。Doug Crockford 对这些功能做了很好的介绍,并提供了更详细描述的链接 这里。
This sort of thing can only be done in ECMAscript 5 which is not supported in all browsers (e.g. IE). Using
Object.defineProperty
you can create properties with accessor functions - so you could implement a property likelength
in arrays that varies, depending on the object state.There's a good presentation from Doug Crockford about these features and with links to more detailed descriptions here.