从JS中的另一个函数调用方法(TypeError异常)

calling a method from another function in JS (TypeError exception)

本文关键字:TypeError 异常 方法 函数调用 JS 另一个      更新时间:2023-09-26

我想这真的是一个新手错误,但我不能使它运行。我有一个"计算器"对象t,它包含了很多计算值的函数。我需要从我的"计算器"对象中使用这些函数来获取另一个函数中的一些值。我将其简化为以下内容,但是当我调用t.h hello()方法时,我得到了TypeError异常。什么好主意吗?

 var t = new T();
 two();
 function T() {
     function hello() {
         alert("hello");
     }
 }
 function two() {
     t.hello();
 }
http://jsfiddle.net/4Cc4F/

您需要返回一个包含以下函数的对象:

function T() {
    return {
        'hello': function () {
            alert("hello");
        }
    }
}

或者将其定义为T范围内的函数:

function T() {
    this.hello = function() {
        alert("hello");
    }
}

小提琴

函数helloT的局部作用域中

这样定义T

function T() {
     this.hello = function() {
         alert("hello");
     }
 }

试试这个,

var t = new T();
two();
function T() {
     this.hello = function () {
         alert("hello");
     }
 }    
 function two() {    
     t.hello();    
 } 

看到这个:http://jsfiddle.net/4Cc4F/2/