gpt4 book ai didi

javascript - 如何在原型(prototype)函数中访问javascript对象变量

转载 作者:可可西里 更新时间:2023-11-01 02:56:52 24 4
gpt4 key购买 nike

我有以下javascript

function person() {
//private Variable
var fName = null;
var lName = null;

// assign value to private variable
fName = "Dave";
lName = "Smith";
};

person.prototype.fullName = function () {
return this.fName + " " + this.lName;
};

var myPerson = new person();
alert(myPerson.fullName());

我正在尝试了解 javascript 中面向对象的技术。我有一个简单的人对象,并在其原型(prototype)中添加了一个函数。

我原以为警报会显示“Dave Smith”,但我得到的是 “underfined underfined”。为什么会这样,我该如何解决?

最佳答案

很遗憾,您无法访问私有(private)变量。因此,要么将其更改为公共(public)属性,要么添加 getter/setter 方法。

function person() {

//private Variable
var fName = null;
var lName = null;

// assign value to private variable
fName = "Dave";
lName = "Smith";

this.setFName = function(value){ fName = value; };
this.getFName = function(){ return fName; }
};

参见 javascript - accessing private member variables from prototype-defined functions


但实际上这看起来像您要找的东西: Javascript private member on prototype

来自那个 SO 帖子:

As JavaScript is lexically scoped, you can simulate this on a per-object level by using the constructor function as a closure over your 'private members' and defining your methods in the constructor, but this won't work for methods defined in the constructor's prototype property.

在你的情况下:

var Person = (function() {
var store = {}, guid = 0;

function Person () {
this.__guid = ++guid;
store[guid] = {
fName: "Dave",
lName: "Smith"
};
}

Person.prototype.fullName = function() {
var privates = store[this.__guid];
return privates.fName + " " + privates.lName;
};

Person.prototype.destroy = function() {
delete store[this.__guid];
};

return Person;
})();


var myPerson = new Person();

alert(myPerson.fullName());

// in the end, destroy the instance to avoid a memory leak
myPerson.destroy();

查看现场演示 http://jsfiddle.net/roberkules/xurHU/

关于javascript - 如何在原型(prototype)函数中访问javascript对象变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6784927/

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