Javascript 属性重载 ala PHP?

发布于 2024-09-27 13:56:16 字数 539 浏览 0 评论 0原文

我正在尝试找到一种像 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寄人书 2024-10-04 13:56:16

这种事情只能在 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 like length 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文