var 创建一个仅在声明它的函数范围内可用的局部变量(在您的问题中是构造函数)。
this.name = xxx 将属性分配给刚刚在构造函数中创建的当前对象,并且任何引用该对象的人都可以使用该属性。
在使用new 运算符调用对象构造函数时,this 被设置为构造函数及其原型中定义的类型的新创建对象。因此,要引用该对象实例的属性,您必须使用 this.xxx。
因此,您必须使用这两种技术中的任何一种来匹配您想要做的事情。有var的构造函数中局部变量的情况,也有初始化实例变量的情况。
这里是一个不同的例子:
实例变量:
function Person(name, family) {
this.name = name;
this.family = family;
}
Person.prototype.getFull = function() {
return this.name + " " + this.family;
};
var p = new Person("Bob", "Smith");
console.log(p.name); // "Bob"
局部变量:
function Person(name, family) {
var aName = name;
var aFamily = family;
// these variables are local and only available
// within the scope of the constructor
}
Person.prototype.getFull = function() {
// this.name and this.family are not defined
return this.name + " " + this.family;
};
var p = new Person("Bob", "Smith");
console.log(p.aName); // undefined
console.log(p.aFamily); // undefined
额外功劳:私有实例变量
有一个混合模型,您可以在构造函数中定义方法,然后这些方法只能访问构造函数中的局部变量。这些变量然后表现得像“私有”实例变量。它们在技术上不是对象的属性,但由于创建了闭包,构造函数中定义的任何方法都可以使用它们。这是私有实例变量的巧妙技巧。这是一个例子:
function Person(name, family) {
var aName = name;
var aFamily = family;
// define method within the constructor that has access to
// local variables here
this.getFull = function() {
return aName + " " + aFamily;
}
}
var p = new Person("Bob", "Smith");
console.log(p.getFull()); // "Bob Smith"
console.log(p.aName); // undefined, not instance properties
console.log(p.aFamily); // undefined, not instance properties