gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 15:40:02 25 4
gpt4 key购买 nike

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

最佳答案

var 创建一个局部变量,该变量仅在声明它的函数范围内可用(在您的问题中为构造函数)。

this.name = xxx 为刚刚在构造函数中创建的当前对象分配一个属性,并且任何引用该对象的人都可以使用该属性。

在对象构造函数中,当使用 new 运算符调用时,this 将设置为构造函数中定义的类型及其原型(prototype)的新创建对象。因此,要引用该对象实例的属性,您必须使用 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

额外奖励:私有(private)实例变量

有一个混合模型,您可以在构造函数中定义方法,然后这些方法只能访问构造函数中的局部变量。这些变量的行为就像“私有(private)”实例变量。从技术上讲,它们不是对象的属性,但由于创建了闭包,它们可用于构造函数中定义的任何方法。对于私有(private)实例变量来说,这是一个巧妙的技巧。这是一个例子:

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

关于javascript - 我们可以在 javascript 的构造函数中放入什么变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32662108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com