【问题标题】:JavaScript OOP - notation confusionJavaScript OOP - 符号混淆
【发布时间】:2019-04-16 08:35:30
【问题描述】:

我想知道这些符号有什么区别:

function Forms (formSelector) {
  this.id;
  this.formSelector = formSelector;
}

Forms.prototype.getAll = function () { return $(this.formSelector) } // get all forms in a JQuery object

Forms.prototype.get = function () { return $(this.getAll()).get(this.id) }

function Forms (formSelector) {
  this.id;
  this.formSelector = formSelector;

  this.getAll = function () { return $(this.formSelector) }
  this.get = function () { return $(this.getAll()).get(this.id) }
}

甚至

function Forms (formSelector) {
  this.id;
  this.formSelector = formSelector;

  this.getAll = $(this.formSelector);
  this.get = $(this.getAll()).get(this.id);
}

我什至可以这样写:

var Forms = {
  constructor: function (formSelector) {
    this.formSelector = formSelector;

    return this.formSelector;
  },

  setId: function (id) { if (!isNaN(id) this.id = id; }

  getAll: function () {
    return $(Forms.constructor.formSelector); // this should work I think ?
   }
}

这让我很困惑,我不太清楚在速度和清晰度以及封装它们的方法和属性方面,编写对象的最佳和更优化的方法是什么。

无论如何,我似乎可以通过以下方式修改我的属性:

var test = new Forms('.forms');

test.id = 10;
test.getAll = 'something';

// What I want is something like :

test.setId(10) // and test.id = X shouldn't work

谢谢!

【问题讨论】:

  • @Phiter 我不认为它是骗子
  • @Rajesh 接受的答案回应了这个确切的事情。至少前两个例子。
  • 至少前两个例子意味着有些东西它没有回答
  • 第三个例子不同,因为你返回的是一个对象,而不是一个函数。所以这个对象可以改变为如果它是在函数本身中创建的,你不能直接修改函数的对象。
  • @Rajesh 应该将多个问题标记为重复

标签: javascript jquery oop


【解决方案1】:

现在是 2018 年,现在几乎所有浏览器都支持 ES6 类,当然除了 IE 11。但是如果你想支持旧的浏览器,你可以使用 babel 来转译你的代码。

话虽如此,这就是您在 JavaScript 中编写 class OOP 方式的方式。

class Form {
    constructor(formSelector) {
      this.id = 'default value';
      this.formSelector = formSelector;
      // probably also check if $ is defined
    }

    // you can use getter method
    get id() {
      return this.id;
    }

    // you can use setter method
    set id(idVal) {
      this.id = idVal;
    }

    get formSelector() {
      return this.id;
    }

    set formSelector(val) {
      this.formSelector = val;
    }

    getAll() {
      return $(this.formSelector);
      // whatever getAll is supposed to return
    }
}

你可以使用这个类

const myForm = new Form('form-selector-value');

// no brackets for getter and setter
const formId = form.id; // get id value
form.id = 'some-val'; // set id value

form.getAll(); // invoke the get all method

// you can change the formSelector anytime for `form` variable
form.formSelector = 'some-value';

【讨论】:

  • 谢谢,这很高兴知道,它看起来更像我所知道的。不幸的是,在 IE 支持之前我不能使用这种表示法。我尽量让我的代码尽可能简单,以便大多数浏览器都支持它,这意味着我尽量不使用 JQuery 以外的任何库。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-07
  • 1970-01-01
相关资源
最近更新 更多