我更喜欢在大型项目中使用OOP,比如我现在正在做的项目.我需要用JavaScript创建几个类,但是,如果我没有弄错的话,至少有几种方法可以做到这一点.语法是什么?为什么要这样做?
我希望避免使用第三方库——至少一开始是这样
我更喜欢在大型项目中使用OOP,比如我现在正在做的项目.我需要用JavaScript创建几个类,但是,如果我没有弄错的话,至少有几种方法可以做到这一点.语法是什么?为什么要这样做?
我希望避免使用第三方库——至少一开始是这样
以下是在不使用任何外部库的情况下完成此操作的方法:
// 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"
现在,真正的答案要复杂得多.例如,JavaScript中没有类这样的东西.JavaScript使用基于prototype
的继承方案.
此外,还有许多流行的JavaScript库,它们有自己的风格来近似JavaScript中的类功能.你至少要判断Prototype和jQuery.
Deciding which of these is the "best" is a great way to start a holy war on 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. I'm a Prototype guy, but Stack Overflow seems to lean towards jQuery.
就只有"一种方法"而言,没有任何对外部库的依赖,我写的方法基本上就是这样.