繁体   English   中英

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

[英]What variable can we put inside the construction function in javascript?

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; this.name = name; this.family = family; 为什么这样 为什么我们不能只做var name1 = name

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

您可以执行var name1 = name。 但是然后,此变量将成为person范围内的私有变量,并且您的原型或person范围外的任何内容都无法在父函数内部没有用作返回该var的get函数的属性的情况下直接访问它们。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM