这些 Javascript 函数声明的差异

Differences in these Javascript function declarations

本文关键字:声明 Javascript 函数 这些      更新时间:2023-09-26

今天我看到了两种不同类型的Javascript函数声明,我想对这两种声明有更深入的了解:

function Car( model, year, miles ){
   this.model = model;
   this.year    = year;
   this.miles  = miles;
}
/*
 Note here that we are using Object.prototype.newMethod rather than 
 Object.prototype so as to avoid redefining the prototype object
*/
Car.prototype.toString = function(){
    return this.model + " has done " + this.miles + " miles";
};
var civic = new Car( "Honda Civic", 2009, 20000);
var mondeo = new Car( "Ford Mondeo", 2010, 5000);
console.log(civic.toString());

和类型 2:

function Car( model, year, miles ){
   this.model = model;
   this.year    = year;
   this.miles  = miles;
   this.toString = function(){
       return this.model + " has done " + this.miles + " miles";
   };
}

var civic = new Car( "Honda Civic", 2009, 20000);
var mondeo = new Car( "Ford Mondeo", 2010, 5000);
console.log(civic.toString());

特别是"原型"和"this.toString"。

谁能传授一些JS智慧的珍珠?

这里的主要区别在于,在方法 2 中,您将使用您创建的 Car 的每个新实例重新定义该方法,这在技术上性能较差。

然而,方法 2 确实为您提供的一件好事是您可以创建真正的私有实例变量,如下所示:

function Person( _age ){
    var age = _age;
    this.canDrink = function(){
        return age >= 21;
    }
}
var p = new Person(25);
p.canDrink() // true
p.age // undefined, because age is not exposed directly

方法 1 的另一个优点(除了性能)是,您现在可以更改 on 对象的所有实例的功能。例如:

function Person( _age ){
    this.age = _age;
}
Person.prototype.canDrink = function(){
    return this.age >= 21;
}
var a = new Person(15),
    b = new Person(25);
a.canDrink() // false
b.canDrink() // true
Person.prototype.canDrink = function(){ return true }
a.canDrink() // true
b.canDrink() // true

这在方法 2 中是不可能的(不为每个实例更改它)。然而,年龄现在暴露在外:

a.age // 15
b.age // 25

this.toString必须在构造函数中定义,并且只能在 Car 类中找到,而不是从它继承的任何内容(除非特别包含在子类中)。

Car.prototype.toString可以在构造函数外部定义,并且可以在从 Car 类继承的任何类的原型中找到。