javascript中的空白输出

时间:2014-04-12 05:03:39

标签: javascript

Helo朋友我编写了一个js脚本来找出函数中的值。代码是

function hello(this) {
this.value = 10;
document.write(this);
};


var c = new hello(c);
c();

但我得到这个输出为空白...我知道这取决于函数的调用方式,这里c是这个值。所以输出必须是c。

我想在这里改变new hello(to any string)还是像我一样改变。{/ p>

请帮我解决这个问题并让我纠正......任何帮助都会受到赞赏..谢谢..

3 个答案:

答案 0 :(得分:0)

嗯,首先你不能使用"这个"作为javascript中的变量,因为它是一个保留关键字,你最好使用其他东西。其次,如果要将字符串传递给函数,则必须将其括在单引号(')或双引号(")之间。第三,您的函数不返回任何值,因此不需要将其分配给变量。第四,你要在" ths"对象,但如果你知道我的意思,你就不会返回。那是我的评论。您的代码更正将是:

function hello(ths) {
document.write(ths);
};

hello("your string goes here");

答案 1 :(得分:0)

尝试:

/* incoming variable we set when calling our function, currently reads: Hello there! */
var hello = function(incoming) { 
     /* incoming variable being overwritten, now reads: 10 */
     incoming = 10; 
     /* writing 10 to document, overwriting anything already written to document */
     document.write(this); 
};
/* calling your function 'hello' as well as setting incoming variable to: Hello there! */
var a = new hello('Hello there!');

答案 2 :(得分:0)

框架结构,扎实。我假设你是在追求这样的事情?

function hello ()
{
    // inside a function (soon to be object) "this" refers to that object
    this.value = 10; // can and must be called by c.value outside of the declared function

    this.sayHello = function( msg )
    {
        this.value = msg; // is equal to c.value (outside of hello), overwrites old value with new message
        document.write( msg );
    }
}

// 'new' prefix types an object, represented by 'c'
var c = new hello;

c.sayHello( 'your message' );
// Your most recent message is stored in c.value