何时在javascript中使用this而不是object literal

when to use this and not object literal in javascript?

本文关键字:object literal this javascript 何时      更新时间:2023-09-26

我读过JS中的OOP,但混淆了传统OOP和对象文字。我还发现,在github中,许多伟大的JS项目并不是用"OOP方式"编写的。它们利用了对象的整体模式,如揭示模式和单体。我来自Java,现在我在以下模式之间徘徊,不知道何时使用它们。

OOP:

function cook(){
this.vege = 'something';
}
var Cook = new cook();
console.log(Cook.vege = 'something else')

对比对象文字方式:

var cook = {
vege:"something"
}
cook.vege = "something else"

通常,您只需要一个对象文字。但是,如果您想要使用相同的模式创建多个对象实例,则应该使用构造函数来避免重复。如果你想在实例之间共享一些东西,比如方法,这一点也很重要:

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');

并且它们都将具有CCD_ 1和CCD_。

比方说,为一个特定的学生创建了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();

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