我是 JavaScript 新手。
如何在 javascript 中声明一个类,例如使用名为 username 的属性。
然后在用户名属性赋值后运行一个函数。
在 C# 中,它是这样的:
public int M_A
{
get
{
return m_a;
}
set
{
m_a = value;
RunFunction();
}
}
最佳答案
Javascript 没有基于类的继承,它使用基于原型(prototype)的继承。此外,它不提供对 getter 和 setter 的支持(在大多数版本中)。
这是编写示例的一种方法:
var ExampleClass = function(){
var _m_a;//private instance
this.m_a = function(){
if(arguments.length){
_m_a = arguments[0];
}else{
return _m_a;
}
};
};
用法:
var inst = new ExampleClass();
inst.m_a(5);//provide an argument to set it
console.log(inst.m_a());//no arguments to get it
由于我们只是近似一个类系统,因此实际上有几种方法可以做到这一点。这是另一个:
var ExampleClass = function(){
this._m_a = null;
};
ExampleClass.prototype.get_m_a = function(){
return this._m_a;
};
ExampleClass.prototype.set_m_a = function(value){
this._m_a = value;
};
用法:
var inst = new ExampleClass();
inst.set_m_a(5);
console.log(inst.get_m_a());
console.log(inst._m_a);//annoying thing is the private property is accessible
为了更好地理解原型(prototype)继承和 javascript 类系统,请查看这些帖子:
关于JavaScript 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6248333/