创建像C#属性的javascript属性 [英] Create javascript property like C# property

查看:83
本文介绍了创建像C#属性的javascript属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在javascript对象上创建一个与C#中的属性类似的属性。

Is it possible to create a property on a javascript object that behaves similar to a property in C#.

示例:
我创建了一个自动使用dojo调整textarea小部件。为了从我的小部件中获取value属性,我已经连接到onchange事件,每次textarea的值发生变化时我都会设置一个变量。

Example: I've created an auto-sizing textarea widget using dojo. In order to get the "value" property out of my widget, I've hooked up to the onchange event and I'm setting a variable everytime the value of the textarea changes.

有没有办法在不连接onchange事件的情况下完成此任务。

Is there a way to accomplish this without hooking up to the onchange event.

编辑

换句话说,是否可以在JavaScript中写一些行为类似于getter和/或setter的内容。

In other words, is it possible to write something in JavaScript that behaves like getters and/or setters.

推荐答案

ECMAScript 5实现中可能包含所有主流浏览器的最新版本 。 ECMAScript 5规范增加了标准化的getter和setter。一个怪癖是IE 8具有此功能,但仅限于DOM节点。这就是语法:

It is possible in ECMAScript 5 implementations, which include recent versions of all major browsers. The ECMAScript 5 spec adds standardized getters and setters. One quirk is that IE 8 has this feature, but only on DOM nodes. This is what the syntax looks like:

var obj = {};

Object.defineProperty(obj, "value", {
    get: function () {
        return this.val;
    },
    set: function(val) {
        this.val = val;
    }
});

在Mozilla中也有一个专有的getter和setter实现很长一段时间了由WebKit和Opera采用,但这在IE中不可用。

There has also been a proprietary implementation of getters and setters in Mozilla for a long time that was also later adopted by WebKit and Opera but this is not available in IE.

这篇关于创建像C#属性的javascript属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆