虽不能至,心向往之

—— 巴人也,操C++口音,混迹于京师,勉强度日……《史记·corelito列传》
posts - 8, comments - 15, trackbacks - 0, articles - 0

使用V8——Google Chrome 的 JavaScript 引擎(4)

Posted on 2008-10-20 23:06 sufan 阅读(2085) 评论(0)  编辑 收藏 引用 所属分类: 翻译
打印
“print” 函数将会是我们自定义的另外一个函数,它通过使用 printf 函数将所接受的参数全部打印出来。和先前“plus”函数一样,我们需要在全局模板中注册这个新函数:

//associates print on script to the Print function
global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print)); 

实现“print”函数

// The callback that is invoked by v8 whenever the JavaScript 'print'
// function is called. Prints its arguments on stdout separated by
// spaces and ending with a newline.
v8::Handle<v8::Value> Print(const v8::Arguments& args) 
{
    
bool first = true;
    
for (int i = 0; i < args.Length(); i++)
    {
        v8::HandleScope handle_scope;
        
if (first)
        {
            first 
= false;
        }
        
else
        {
            printf(
" ");
        }
        
//convert the args[i] type to normal char* string
        v8::String::AsciiValue str(args[i]);
        printf(
"%s"*str);
    }
    printf(
"\n");
    
    //returning Undefined is the same as returning void...
    return v8::Undefined();
}

 

针对每个参数,需要构造一个 v8::String::AsciiValue 对象为传递值创建一个 char * 的表示。有了它,我们就能把其他类型转换为相应的字符串表示,并将它打印出来!

JavaScript 小样
现在,我们已经可以在 demo 程序中使用这个 JavaScript 小样了。

print("begin script");
print(script executed by  
+ user);
if ( user == "John Doe"){
    print(
"\tuser name is invalid. Changing name to Chuck Norris");
    user 
= "Chuck Norris";
}
print(
"123 plus 27 = " + plus(123,27));
= plus(3456789,6543211);
print(
"end script");

这段脚本使用到了“x”变量,“user”变量,以及“plus”函数和“print”函数。


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理