在 Javascript 对象中调用方法 [英] Calling a method within a Javascript Object

查看:72
本文介绍了在 Javascript 对象中调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个可以在自身内部调用其他方法的 javascript 对象.但是,我遇到了一个我似乎无法弄清楚的奇怪问题.

I'm trying to create a javascript object that can call other methods within itself. However, I'm running into a weird problem that I just can't seem to figure out.

我有以下代码

myObjectDef = function() {
    this.init = function() {
        //do some stuff
        this.doSecondInit();
    }
    this.doSecondInit = function() {
        //do some more stuff
    }
}

myObject = new myObjectDef();
myObject.init();

我收到一条错误消息,指出消息:对象不支持此属性或方法".它以 this.doSecondInit(); 结束.我不太明白为什么要这样做.我的代码在调用第二种方法之前运行良好.我该怎么做?

I am getting an error that states "Message: Object doesn't support this property or method". And it ends at this.doSecondInit();. I can't quite figure out why it's doing this. My code runs great up to the call to the second method. How do I make this work?

推荐答案

这里有一组额外的括号:

There's an extra set of parenthesis here:

this.doSecondInit() = function() {

您不能分配给函数调用的结果,更不用说分配给一个甚至不存在的函数的结果了.

You can't assign to the result of a function call, let alone to the result of a function that doesn't even exist.

在您编辑之后,您的东西似乎工作正常:

After your edit, your thing seems to work fine:

http://jsfiddle.net/nabVN/

您确定您的实际代码中没有相同的错字?最好开始习惯不要在每次函数调用后放置 (),这可能是从函数不是值的语言中延续下来的坏习惯.

You sure you didn't have the same typo in your actual code? Better start getting used to not putting that () after every function call, which is probably a bad habit carried over from languages where functions aren't values.

这篇关于在 Javascript 对象中调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆