【问题标题】:when to use this and not object literal in javascript? [duplicate]何时在 javascript 中使用 this 而不是对象文字? [复制]
【发布时间】:2023-04-09 01:10:01
【问题描述】:

我正在阅读 JS 中的 OOP,但对传统的 OOP 和对象字面量感到困惑。而且我还在 github 中发现很多很棒的 JS 项目并不是用“OOP 方式”编写的。他们利用对象字母模式,如显示模式和单例。我来自 Java,现在我对以下模式感到困惑,何时使用它们。

面向对象:

function cook(){
this.vege = 'something';
}

var Cook = new cook();
console.log(Cook.vege = 'something else')

与对象字面量方式:

var cook = {

vege:"something"

}
cook.vege = "something else"

【问题讨论】:

    标签: javascript jquery oop


    【解决方案1】:

    通常,您只需要一个对象字面量。但是,如果您想使用相同的模式创建多个对象实例,您应该使用构造函数来避免重复自己。如果您想跨实例共享诸如方法之类的东西,这一点也很重要:

    function Cook(name) {
      this.name = name;
      this.vege = 'something';
    }
    
    Cook.prototype = {
      cookSomething: function () { ... },
      doDishes: function () { ... }
    };
    

    现在你可以这样做了:

    var fred = new Cook('Fred');
    var lisa = new Cook('Lisa');
    

    ...它们都有cookSomethingdoDishes 方法。

    【讨论】:

      【解决方案2】:

      假设为某个学生创建了 100 个对象:

      var Student = function (name) {
        this.name = name;
        this.greet = function () {
          console.log("My name is " + this.name);
        };
      };
      
      var praveen = new Student("Praveen Kumar");
      var hello = new Student("Hello, World!");
      var jeff = new Student("Jeff Atwood");
      
      praveen.greet();
      hello.greet();
      jeff.greet();

      但是,如果我突然想添加另一个函数,比如greet() 函数到:

      console.log("Hola! This is " + this.name);
      

      现在“类”就派上用场了。

      var Student = function (name) {
        this.name = name;
        this.greet = function () {
          console.log("My name is " + this.name);
        };
      };
      
      var praveen = new Student("Praveen Kumar");
      var hello = new Student("Hello, World!");
      var jeff = new Student("Jeff Atwood");
      
      Student.prototype.sayHola = function () {
        console.log("Hola! This is " + this.name);
      };
      
      praveen.sayHola();
      hello.sayHola();
      jeff.sayHola();

      添加一个原型比继续添加所有对象更容易。这会将函数添加到所有对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-06
        • 1970-01-01
        • 2012-05-29
        • 2020-12-02
        • 2018-01-30
        • 2023-03-03
        • 2016-01-04
        相关资源
        最近更新 更多