[英]Differences in these Javascript function declarations
Today I saw two different types of Javascript function declarations and I'd like to have a deeper understanding of the two: 今天,我看到了两种不同类型的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());
and type 2: 并输入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());
Specifically the 'prototype' and the 'this.toString'. 特别是“原型”和“ this.toString”。
Can anyone impart some pearls of JS wisdom? 谁能传授一些JS智慧的明珠?
The primary difference here is that in method 2 you are redefining the method with every new instance of Car you create, which is technically less performant. 此处的主要区别在于,在方法2中,您将使用创建的Car的每个新实例重新定义该方法,这在技术上是性能较低的。
One nice thing method 2 does afford you however is that you can create truly private instance variables, like so: 方法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
Another advantage to method 1 (besides performance) is that you can now change the functionality of all instances of on object. 方法1的另一个优点(除了性能)是,您现在可以更改on对象的所有实例的功能。 For example:
例如:
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
this would not be possible with method 2 (without changing it for every instance). 方法2(在每个实例中都不要更改)将是不可能的。 Age however, is now exposed:
但是,现在暴露出年龄:
a.age // 15
b.age // 25
this.toString
must be defined within the constructor and will only be found on the Car class, not anything inheriting from it (unless specifically included on children classes). this.toString
必须在构造函数中定义,并且只能在Car类上找到,而不能从其继承任何类(除非专门包含在子类中)。
Car.prototype.toString
can be defined outside of the constructor and will be found on the prototypes of any classes inheriting from the Car class. Car.prototype.toString
可以在构造函数之外定义,并且可以在从Car类继承的任何类的原型中找到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.