如何在Javascript中创建OOP类 [英] How to create OOP Class in Javascript

查看:67
本文介绍了如何在Javascript中创建OOP类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用任何教程犹豫不决,因为我知道这些教程最终会如何,教会你做坏事的方法。我想在Javascript中设置一个类,这样我就可以了。

I'm hesitant to use just any tutorial because I know how those tutorials can end up being, teaching you bad ways to do things. I want to setup a class in Javascript, so that I can just do

var vehicle = new Vehicle(el);
var model = vehicle->getModel();

这些函数会读取HTML并获取和管理页面上的元素。我现在做的设置就像......

These functions would read the HTML and get and manage the elements on the page. I'm current doing a setup like...

var model = function () {
 return {
  getName: function () {

  },
  getVehicleCount: function () {

  },
  incrementCount: function (id) {
   console.log(x);
  }
 }
}();

我还在学习Javascript课程...我希望能够通过class所有方法将使用的元素的节点,但我不确定我是否正确...

I'm still learning classes in Javascript... I'd like to be able to pass the class a node for the element all of the methods will use, but I'm not sure I'm doing this right...

推荐答案

JavaScript中没有类这样的东西,而JavaScript中的所有内容都是对象。

There is no such thing as a class in JavaScript, instead everything in JavaScript is an object.

要创建新对象,您需要定义一个使用中包含此关键字(构造函数),然后使用 new 运算符调用它:

To create a new object you define a function that uses the this keyword in it (a "constructor function"), and then call it with the new operator:

function Foo (id) { // By convention, constructor functions start with a capital letter
    this.id = id;
}

var foo1 = new Foo(1);
var foo2 = new Foo(2);

但是,这些对象没有方法。要添加方法,需要在构造函数上定义原型对象:

However, these objects have no methods. To add methods, you need to define a prototype object on their constructor function:

Foo.prototype = {
    getId: function () {
        return this.id;
    }
}

这个新的 getId Foo 对象都可以使用code>函数。但是,如上所述,JavaScript中没有类,因此您将使用其他结构来产生不同的结果。

This new getId function will be usable by all Foo objects. However, as was stated, there are no classes in JavaScript and as such there are other constructs you will use in order to produce different results.

我强烈推荐视频道格拉斯克罗克福德,他解释了很多javascript的性质。会谈可以在这里找到:

I highly recommend the videos by Douglas Crockford in which he explains much of the javascript OO nature. The talks can be found here:

http ://developer.yahoo.com/yui/theater/

Douglas Crockford - JavaScript编程语言

Douglas Crockford — The JavaScript Programming Language

Douglas Crockford - 高级JavaScript

Douglas Crockford — Advanced JavaScript

这些将使您对javascript结构有一个基本的了解,并且应该有助于从经典编程转换为函数式编程。

Those will give you a basic understanding of the structure of javascript and should help the transition from classical to functional programming.

这篇关于如何在Javascript中创建OOP类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆