Fla*_*nix 8 javascript ecmascript-6
我是一名开发人员,拥有大约9年的Java和C#背景历史.
在那些语言中,类和分类分类以及对象范例固有.
因此,当ECMA6出来时,我很高兴看到语言课程......我开始在各处使用它们.
事实证明,在JavaScript中使用类是一个陷阱.
你永远不会真正理解JavaScript.你会认为你这样做,但你没有.
很明显,在看完这个完整的会议后,我意识到我不懂JavaScript.
我的生活中我已经使用OOP格式化了类范例,现在我甚至不知道在哪里寻求帮助,甚至不知道如何开始.
非JavaScvript的一个例子:
class Animal{
constructor(aName){
this.name = aName;
}
}
class Dog extends Animal{
constructor(){
super(aName);
this.type = "Furry dog";
}
}
let myDog = new Dog("Boby");
Run Code Online (Sandbox Code Playgroud)
在这一点上,我正在寻找指导.在尝试之后我找不到任何有用的东西,主要是因为我相信我迷失了以至于我甚至都没有找到正确的东西.
提前致谢.
据我所知,JavaScript是一种基于Prototype的语言,具有一流的功能,你可以在这里阅读.
现在.实际上,这只是一种OPP风格,意味着你将在工作和思考对象和继承.你只需要知道,在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;
};
// Here we create an instance of Animal
var someAnimal = new Animal();
// Let's give it a name
someAnimal.name = 'Dobby';
console.log('Hey there. My pet name is %s', someAnimal.name);
console.log('is it wild? %o', someAnimal.isWild);
Run Code Online (Sandbox Code Playgroud)
现在你有了动物原型.让我们看看如何扩展其属性以创建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!);
};
Run Code Online (Sandbox Code Playgroud)
让我们现在创造一个狗的种族:
function SiberianHusky(name, age) {
this.name = name;
this.age = age;
this.race = 'Siberian Husky';
}
SiberianHusky.prototype = Object.create(Dog.prototype);
SiberianHusky.prototype.constructor = SiberianHusky;
// Let's create our Siberian Husky
var myPet = new SiberianHusky('Bobby', 5);
// Aww. It is barking!
myPet.bark();
Run Code Online (Sandbox Code Playgroud)
您可以在示例中看到每个定义都使用Object 原型.这用于定义对象的方式.您可以将其视为类定义.
您可以执行以下操作,而不是每次都写入原型:
Animal.prototype = {
name: null,
age: 0,
genus: null,
isWild: true,
hasName: function() { ... }
isItWild: function() { ... }
}
Run Code Online (Sandbox Code Playgroud)
要完全理解原型的概念以及它们如何从彼此继承,您可以检查它.
JavaScript是一种多范式语言.您可以使用面向对象编程范例,命令式编程范例和函数式编程范例,这意味着您可以通过多种不同方式对同一应用程序进行编程.
https://en.wikipedia.org/wiki/JavaScript
https://en.wikipedia.org/wiki/Prototype-based_programming
干杯.
| 归档时间: |
|
| 查看次数: |
1071 次 |
| 最近记录: |