【问题标题】:Javascript OOP prototype functions return undefinedJavascript OOP 原型函数返回未定义
【发布时间】:2015-01-13 18:24:35
【问题描述】:

我试图理解 javascript 中的 OOP 并编写了这两个文件。我的问题是原型函数的意外结果:未定义。

我是否错过了什么或做错了什么?

模块:

/*jslint node: true */

function User(tid, tname, ttype) {
    'use strict';
    this.id = tid;
    var name = tname,
        type = ttype;

    console.log("user: " + this.id + " created.");
}

User.prototype.getName = function () {
    'use strict';
    return this.name;
};

User.prototype.getType = function () {
    'use strict';
    return this.type;
};

module.exports = User;

这实现了类:

/*jslint node: true */
var User = require('./User');

var userlist = [];

function init() {
    'use strict';
    var namelist = ['Boz', 'Nash', 'Joe', 'Angel'],
        i = 0,
        tUser;

    for (i = 0; i < namelist.length; i += 1) {
        tUser = new User(i + 1, namelist[i], 0);

        userlist.push(tUser);

    }
}

function print() {
    'use strict';
    var tString,
        i;

    for (i = 0; i < userlist.length; i += 1) {
        tString = "User Entry:" + i + " | ";
        tString += userlist[i].getName() + " | ";
        tString += userlist[i].getType() + " | ";
        tString += userlist[i].id;
        console.log(tString);
    }
}

init();
print();

这是输出:

user: 1 created.
user: 2 created.
user: 3 created.
user: 4 created.
User Entry:0 | undefined | undefined | 1
User Entry:1 | undefined | undefined | 2
User Entry:2 | undefined | undefined | 3
User Entry:3 | undefined | undefined | 4

【问题讨论】:

  • 您的对象实例上没有 name 属性,只有 id
  • 我想将变量名称和类型设为私有,以便在实例化对象时它们只获得一次值。然后只有 getter 函数获取值。我认为那是不可能的?
  • JS 中没有私有属性这样的东西。好的,有一种非常丑陋的方法可以使用非严格方法(通过 arguments.callee.caller)来强制执行私有属性,但我怀疑这就是你想要的。
  • 感谢@dandavis 我投票支持rfornals 回复并相应地编辑我的代码。

标签: javascript oop scope


【解决方案1】:

这里的问题是如何声明和分配变量:

试试...

function User(tid, tname, ttype) {
    'use strict';
    this.id = tid;
    this.name = tname;
    this.type = ttype;

    console.log("user: " + this.id + " created.");
}

变量赋值使其成为本地可访问的变量;使用它允许原型访问变量。使用this 赋值,在你的例子中,变量被赋值给对象User

【讨论】:

  • 我不是说this 是作用域,但作用域是问题......将改写。
  • 范围:取决于视角;当他使用 var 创建变量时,它们的作用域仅在函数内部。我们可以争论这一点,但我会在回答中澄清这一点以结束这篇评论。
【解决方案2】:

那么不要使用私有变量:

this.id = tid;
this.name = tname,
this.type = ttype;

在您的示例中使用var

this.id = tid;//available in other functions
var name = tname,
    type = ttype;//won't allow you to access in other functions

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多