gpt4 book ai didi

javascript - JavaScript 对象中的私有(private)变量定义

转载 作者:行者123 更新时间:2023-11-30 10:16:29 26 4
gpt4 key购买 nike

我正在学习使用原型(prototype)属性在 JavaScript 上定义“类似类”的函数。当我像这样定义一个 People 类时,一切都运行良好:

var People = function(firstName, lastName){
// public
this.firstName = firstName;
this.lastName = lastName;

this.fullName = function(){
console.log(full_name);
return this;
};

// private
var self = this;
var full_name = function(){
return self.firstName + ' ' + self.lastName;
}();
};

var person = new People('John', 'Smith');
person.fullName(); // => "John Smith"

但是,当我将 fullName 方法移动到初始定义之外时,如下所示:

var People = function(firstName, lastName){
// public
this.firstName = firstName;
this.lastName = lastName;

// private
var self = this;
var full_name = function(){
return self.firstName + ' ' + self.lastName;
}();
};

People.prototype.fullName = function(){
console.log(full_name);
return this;
};

var person = new People('John', 'Smith');
person.fullName(); // => "ReferenceError: full_name is not defined"

我遇到了一个错误。我不明白为什么...??

最佳答案

这里:

var full_name = function(){
return self.firstName + ' ' + self.lastName;
}();

您将变量“full_name”设置为调用该匿名函数的结果。然而,它只是在该构造函数的上下文中声明的一个变量,所以这并不重要;构造函数之外的任何东西都无法访问它。

因此在该原型(prototype)函数中,您会得到一个错误,因为“full_name”实际上定义。如果您想在原型(prototype)上使用全名函数,只需在此处声明即可:

People.prototype.fullName = function() {
return this.firstName + " " + this.lastName;
};

如果您想要一个只能由构造函数中的代码访问的“私有(private)”函数,那么您可以这样做:

var People = function(firstName, lastName){
// public
this.firstName = firstName;
this.lastName = lastName;

// private
var self = this;
function fullName(){
return self.firstName + ' ' + self.lastName;
}

this.addressMe = function(msg) {
return fullName() + ": " + msg;
};
};

然后你可以这样做:

var bob = new People("Bob", "Scum");
alert( bob.addressMe("stand and deliver") ); // "Bob Scum: stand and deliver"

关于javascript - JavaScript 对象中的私有(private)变量定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23417263/

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