c# - 将 C# 类转换为 JavaScript

标签 c# javascript class

看看这个基础类:

namespace AcmeWeb
{
    public string FirstName { get; set; }

    public class Person 
    {
        public Person(string firstName, string lastName) 
        {
            if (String.IsNullOrEmpty(firstName))
            {
                throw new ArgumentNullException(firstName);
            }

            this.FirstName = firstName;
        }
    }
}

将此翻译成 JavaScript 的最佳方式是什么?

这是我的想法:

(function(namespace) {

    namespace.Person = function(firstName, lastName) {

        // Constructor

        (function() {
            if (!firstName) {
                throw "'firstName' argument cannot be null or empty";
            }
        })();

        // Private memberts

        var _ = {
            firstName: firstName
        };

        // Public members

        this.firstName = function(value) {
            if (typeof(value) === "undefined") {
                return _.firstName;
            }
            else {
                _.firstName = value;
                return this;
            }
        };

    };

})(AcmeWeb);

最佳答案

您可以在 javascript 中使用真正的 getter/setter。参见 John Resig 的 post想要查询更多的信息。 See the fiddle .

(function(NS) {
    NS.Person = function(firstName, lastName) {
        if (!firstName) {
            throw "'firstName' argument cannot be null or empty";
        }

        var FirstName = firstName;
        this.__defineGetter__("FirstName", function(){
            console.log('FirstName getter says ' + FirstName);
            return FirstName;
        });

        this.__defineSetter__("FirstName", function(val){
            console.log('FirstName setter says ' + val);
            FirstName = val;
        });
    }
})(AcmeWeb);

var p = new AcmeWeb.Person('John', 'Smith');
p.FirstName;          // => FirstName getter says John
p.FirstName = 'Joe';  // => FirstName setter says Joe

关于c# - 将 C# 类转换为 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4511342/

相关文章:

c# - EF CTP5 映射更新失败

c# - Azure:启动远程调试器失败

javascript - 使用一个函数来更新与给定 `id` 匹配的整页 ng-repeat 指令行

javascript - 在 jQuery 中选择下一个 SELECT

java:表示带有可选月份和日期的日期

c++ - 来自类的访问列表,在父类中

c# - `.' 运算符不能应用于 `method group' 类型的操作数 (CS0023) (CurrencyConverter.Droid)

c# - EF 的 DatabaseGeneratedOption.Identity 属性不适用于 ulong 类型

javascript - 当函数位于外部 javascript 文件中时 onclick 事件不起作用

python - type(instance) 何时不同于 instance.__class__?