javascript - 在javascript中的方法中访问对象的成员

标签 javascript prototype methods

为什么我要尝试:

Object(n) //Constructor
{
this.member = n;
}

Object.prototype.alertX = function()// Method
{
alert(this.member);
}

foo = new Object(4);
Object.alertX;

I get "this. member is not defined".

How can i access the constructor's member inside one of its methods?

EDITED: my original purpose is to have an internal method access the already created object member, not to access the object's method from creating another object, the object is already created!

Thanks!

EDITED 2:

Tried this:

var fooObj = function(x,y,z){ // Map object constuctor.
    this.x = x;
    this.y = y;
    this.z = y;
}
fooObj.prototype.test = function(){
    alert(this.x);
}

***initialization****
something = new fooObj();
something.otherMethod(x,y,z); <--- draws an object, a canvas, for example.
document.getElementById('canvas').addEventListener('mouseup', something.test, false);

当我按下该对象时,应该触发警报,但 this.x 未定义。我必须给它一个值吗?该对象已创建并执行其功能之一!

最佳答案

再次编辑...

您的构造函数接受 3 个参数并将它们设置在对象上。您没有在最初的调用中喂养它们。现在,假设您没有遗漏更多信息,请将其更改为:

var fooObj = function(x,y,z){ // Map object constuctor.
    this.x = x;
    this.y = y;
    this.z = y;
}
fooObj.prototype.test = function(){
    alert(this.x);
}

var something = new fooObj(x,y,z);
something.otherMethod(x,y,z); <--- draws an object, a canvas, for example.

否则,如果您遗漏了某些内容,请粘贴代码的完整副本,以免浪费时间。

再次重申,确保正在设置属性。否则解释是它们没有被设置,简单的解释。

function Member(n) {
    this.member = n;
};

Member.prototype.memberNumber = function() { alert( this.member ) };

var john = new Member(1);
john.memberNumber()

或者

function Custom() {
    this.member = 2;
};

Object.prototype.alertX = function() {
    alert( this.member )
}

var x = new Custom();
x.alertX()

"EDITED: my original purpose is to have an internal method access the already created object member, not to access the object's method from creating another object, the object is already created!"

无论您使用什么构造函数或如何设置属性,请确保它已设置。然后只需将一个方法附加到原型(prototype)警报 this.member ,它就会起作用,如果没有,则说明您没有正确设置成员属性。就这么简单。

关于javascript - 在javascript中的方法中访问对象的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1934401/

相关文章:

javascript - JavaScript 表单验证代码的含义?

javascript - 问答游戏的计时器在重新启动时不断加快

javascript - 带有 Socket.IO 的原始 'this' 上下文

java - 添加来自 2 个不同文件的值

java - 使用一种方法将 3 种不同类型的对象添加到一个 ArrayList 的简单方法?

javascript - 检测 ember 文本区域的变化

javascript - 如何获取经过身份验证的用户的数据/id?

javascript - 下划线 Javascript 构建频率图

javascript - 为什么对象原型(prototype)属性不覆盖给定代码

c# - 访问测试类中的方法(缺少指令或程序集引用)?