0

can some one please tell me how can i make the send function read the email object from the next code?

var email = {
    to: '[email protected]',
    subject: 'new email',
    text: 'helloWorld'
}

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

}
send();​

i get this error i also tried to declare the email as follow :

var email = new object(); 

and it didn't work

Uncaught TypeError: object is not a function 

4 Answers 4

4

You are either trying to do this:

var email = { to: '[email protected]', subject: 'new email', text: 'helloWorld' }

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

send();

Or this

function email()
{
    this.to = '[email protected]';
    this.subject = 'new email';
    this.text = 'helloworld';
}

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

send();

I'm not sure which, so I made an example of both. Cheers

Sign up to request clarification or add additional context in comments.

Comments

0

It sounds like you want sendMe to point at the same data email is holding:

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

But if this is the case, you might as well skip the extra variable and just use email directly:

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

Comments

0

You can't use an identifier as an object constructor unless it's a function.

If you want a reference to the object that you created, just copy it from the variable:

var sendMe = email;

Comments

0

You have to return object:

var email = function() {
    return {
        to: '[email protected]',
        subject: 'new email',
        text: 'helloWorld'
    }
};

and then

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

should work.

4 Comments

This will work, but the 'new' keyword is useless in this case. Might as well just write var sendMe = email(); since it's returning a new object
What's the difference? In you answer you use this which basically will do the same with sendMe - it will be same object as in mine. I only showed the way, it's not the perfect code :)
Yes it will result in the same object, but in your code the new keyword is not necessary since the object is being created inside the function anyway. Using the new keyword you are essentially creating two objects and returning one of them. It will work but is not optimal, that's all I'm saying
I've just copied & pasted that part of code from original, so new was incident ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.