函数不读取对象

时间:2012-06-02 23:59:41

标签: javascript jquery json object

有人可以告诉我如何使send函数从下一个代码中读取电子邮件对象?

var email = {
    to: 'google@gmail.com',
    subject: 'new email',
    text: 'helloWorld'
}

function send() {
    var sendMe = new email();
    console.log(sendMe.subject);

}
send();​

我收到此错误我还试图将电子邮件声明如下:

var email = new object(); 

它不起作用

Uncaught TypeError: object is not a function 

4 个答案:

答案 0 :(得分:4)

您要么尝试这样做:

var email = { to: 'google@gmail.com', subject: 'new email', text: 'helloWorld' }

function send()
{
    console.log(email.subject);
}

send();

或者这个

function email()
{
    this.to = 'google@gmail.com';
    this.subject = 'new email';
    this.text = 'helloworld';
}

function send()
{
    var sendMe = new email();
    console.log(sendMe.subject);
}

send();

我不确定是哪一个,所以我做了两个例子。干杯

答案 1 :(得分:0)

听起来您希望sendMe指向email持有的相同数据:

var email = { ...} ;
function send() {
   var sendMe = email;
   console.log(sendMe.subject);
}

但如果是这种情况,你可以跳过额外的变量,直接使用email

var email = { ...} ;
function send() {
   console.log(email.subject);
}

答案 2 :(得分:0)

除非它是函数,否则不能将标识符用作对象构造函数。

如果您想要引用您创建的对象,只需从变量中复制它:

var sendMe = email;

答案 3 :(得分:0)

你必须返回对象:

var email = function() {
    return {
        to: 'google@gmail.com',
        subject: 'new email',
        text: 'helloWorld'
    }
};

然后

function send() {
    var sendMe = new email();
    console.log(sendMe.subject);
}

应该有用。