据我所知,JavaScript是一种基于原型的语言,具有一流函数,你可以在
这里阅读相关信息。
现在,实际上这只是一种面向对象编程风格,这意味着你将会使用和思考对象和继承。你只需知道,在JavaScript中,没有类,但我们有原型代替。但记住,一切都关乎函数。
对象构造器
要创建自己的对象定义,你可以按照以下步骤进行:
function Animal() {
this.name = null;
this.age = 0;
this.genus = null;
this.isWild = true;
};
Animal.prototype.hasName = function() {
return this.name !== null;
};
Animal.prototype.isItWild = function() {
return this.isWild;
};
var someAnimal = new Animal();
someAnimal.name = 'Dobby';
console.log('Hey there. My pet name is %s', someAnimal.name);
console.log('is it wild? %o', someAnimal.isWild);
现在你已经有了Animal原型。让我们看看如何扩展它的属性以创建Dog原型:
function Dog() {
this.genus = 'Canis';
this.race = 'unknown';
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
console.log('rrouff!');
};
现在让我们创建一只狗的种族:
function SiberianHusky(name, age) {
this.name = name;
this.age = age;
this.race = 'Siberian Husky';
}
SiberianHusky.prototype = Object.create(Dog.prototype);
SiberianHusky.prototype.constructor = SiberianHusky;
var myPet = new SiberianHusky('Bobby', 5);
myPet.bark();
原型对象
从这些例子中我们可以看到,每一次定义都使用了Object prototype。这被用来定义一个对象的属性和方法,你可以把它想象成类定义。
如何避免过度使用原型属性
为了避免每次都写入原型,你可以采取以下做法:
Animal.prototype = {
name: null,
age: 0,
genus: null,
isWild: true,
hasName: function() { ... }
isItWild: function() { ... }
}
要完全理解原型的概念以及它们如何相互继承,您可以查看此链接.
最后的说明
JavaScript 是一种多范式语言。您可以使用面向对象编程范式、命令式编程范式和函数式编程范式,这意味着您可以用很多不同的方式编写同一个应用程序。
一些有用的链接
https://en.wikipedia.org/wiki/JavaScript
https://en.wikipedia.org/wiki/Prototype-based_programming
Cheers.