在JavaScript中使用什么而不是类?

Fla*_*nix 8 javascript ecmascript-6

背景

我是一名开发人员,拥有大约9年的Java和C#背景历史.

在那些语言中,类和分类分类以及对象范例固有.

因此,当ECMA6出来时,我很高兴看到语言课程......我开始在各处使用它们.

问题

事实证明,在JavaScript中使用类是一个陷阱.

如果你使用它们,你将会去你的坟墓,从不知道你是多么悲惨.

你永远不会真正理解JavaScript.你会认为你这样做,但你没有.

问题

很明显,在看完这个完整的会议后,我意识到我不懂JavaScript.

我的生活中我已经使用OOP格式化了类范例,现在我甚至不知道在哪里寻求帮助,甚至不知道如何开始.

  1. 在JavaScript风格中,你将如何用继承代表动物王国?我会使用类Animal,然后使用Class Dog,并实例化狗的对象.这不是JavaScript方式.

非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)
  1. 这样做的JavaScript方式是什么?

在这一点上,我正在寻找指导.在尝试之后我找不到任何有用的东西,主要是因为我相信我迷失了以至于我甚至都没有找到正确的东西.

提前致谢.

Asi*_*Paz 9

据我所知,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 原型.这用于定义对象的方式.您可以将其视为类定义.

如何避免过度使用prototype属性

您可以执行以下操作,而不是每次都写入原型:

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

干杯.

  • 我只是分享了我想要帮助的可怜知识.如果你能做得更好,我建议你发一个答案而不是一个评论.谢谢你的意见. (2认同)