看看这个基础类:
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/