Javascript类 [英] Javascript class
问题描述
我是javascript新手。
我如何在javascript中声明一个类,例如使用名为username的属性。
然后在username属性值后运行一个函数。
在C#中它是这样的:
I'm new in javascript.
How can I declare a class in javascript for example with property that named username.
then after username property valued a function is run.
In C# it is something like this :
public int M_A
{
get
{
return m_a;
}
set
{
m_a = value;
RunFunction();
}
}
推荐答案
Javascript没有基于类的继承,它使用基于原型的。此外,它不提供对getter和setter的支持(在大多数版本中)。
Javascript doesn't have a class-based inheritance, it uses a prototype-based. Additionally, it doesn't provide support for getters and setters (in most versions).
这里是一个写您的例子的方法:
Here would be one way to write your example:
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
由于我们只是近似类系统,实际上有几种方法。这是另一个:
Since we're just approximating a class system, there's actually a couple ways to do this. Here's another:
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
为了更好地理解原型继承和javascript类系统,请查看这些帖子:
For a better understanding of prototypal inheritance and javascript class systems, check out these posts:
- Simple JavaScript Inheritance by John Resig (creator of jQuery)
- Classical Inheritance in JavaScript by Douglas Crockford
- JS Class - a Class framework for javascript
这篇关于Javascript类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!