Here's the way to do it without using any external libraries:
(这是无需使用任何外部库即可完成的方法:)
// Define a class like this
function Person(name, gender){
// Add object properties like this
this.name = name;
this.gender = gender;
}
// Add methods like this. All Person objects will be able to invoke this
Person.prototype.speak = function(){
alert("Howdy, my name is" + this.name);
};
// Instantiate new objects with 'new'
var person = new Person("Bob", "M");
// Invoke methods like this
person.speak(); // alerts "Howdy, my name is Bob"
Now the real answer is a whole lot more complex than that.
(现在,真正的答案要复杂得多。)
For instance, there is no such thing as classes in JavaScript.(例如,JavaScript中没有类。)
JavaScript uses a prototype
-based inheritance scheme.(JavaScript使用基于prototype
的继承方案。)
In addition, there are numerous popular JavaScript libraries that have their own style of approximating class-like functionality in JavaScript.
(此外,还有许多流行的JavaScript库,它们具有自己的样式,它们近似于JavaScript中的类功能。)
You'll want to check out at least Prototype and jQuery .(您将至少要签出Prototype和jQuery 。)
Deciding which of these is the "best" is a great way to start a holy war on Stack Overflow.
(确定其中哪一个是“最佳”是在Stack Overflow上展开一场圣战的好方法。)
If you're embarking on a larger JavaScript-heavy project, it's definitely worth learning a popular library and doing it their way.(如果您正着手进行一个较大的JavaScript大型项目,那么绝对值得学习流行的库并按自己的方式去做。)
I'm a Prototype guy, but Stack Overflow seems to lean towards jQuery.(我是一个原型人,但是Stack Overflow似乎倾向于jQuery。)
As far as there being only "one way to do it", without any dependencies on external libraries, the way I wrote is pretty much it.
(就只有“一种方法”,而没有对外部库的任何依赖,我编写的方法就差不多了。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…