如何在原型函数中访问javascript对象变量

Dav*_*hel 9 javascript

我有以下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());
Run Code Online (Sandbox Code Playgroud)

我试图在javascript中理解面向对象的技术.我有一个简单的人物对象,并为其原型添加了一个函数.

我期待警报有"戴夫史密斯",但我得到了"underfined underfined".为什么这样,我该如何解决?

rob*_*les 10

很遗憾,您无法访问私有变量.因此,要么将其更改为公共属性,要么添加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; }
};
Run Code Online (Sandbox Code Playgroud)

javascript - 从原型定义的函数访问私有成员变量


但实际上这看起来像你在寻找: 原型上的Javascript私有成员

来自那篇SO帖子:

由于JavaScript是词法范围的,你可以通过使用构造函数作为对"私有成员"的闭包并在构造函数中定义方法来在每个对象级别上模拟这个,但这不适用于构造函数中定义的方法.原型财产.

在你的情况下:

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();
Run Code Online (Sandbox Code Playgroud)

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


Rob*_*obG 5

当您将person作为构造函数调用时,将创建一个新对象,就像使用关键字new Object()并将其分配给关键字一样.它是默认情况下从构造函数返回的对象.

因此,如果您希望实例具有属性,则需要将它们添加到该对象:

function Person() {

    // assign to public properties
    this.fName = "Dave";
    this.lName = "Smith";
};
Run Code Online (Sandbox Code Playgroud)

顺便提一下,按照惯例,旨在被称为构造函数的函数被赋予以大写字母开头的名称.