我们可以在javascript中的构造函数中放入什么变量?

时间:2015-09-18 22:45:17

标签: javascript function class oop constructor

function Person(name, family) {
    this.name = name;
    this.family = family;
}

Person.prototype.getFull = function() {
    return this.name + " " + this.family;
};

为什么我们必须 this.name = name; this.family = family; ?为什么这个。?为什么我们不能var name1 = name

2 个答案:

答案 0 :(得分:2)

0.292190074921 for dictionary look-up 0.160042047501 for list look-up 0.529402971268 for set construction 0.098151922226 for set reference 创建一个局部变量,该变量仅在其声明的函数范围内可用(在您的问题的情况下为构造函数)。

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

答案 1 :(得分:0)

你可以做var name1 = name。但是这个变量将是人员范围内的私有变量,你的原型或人员范围之外的任何东西都不能直接访问它们而没有父函数内部的属性,该函数作为返回该变量的get函数。

我们使用对象属性,以便可以在父作用域外共享或访问它们。