今天,我看到了两种不同类型的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

09-12 06:12