33
44using namespace v8 ;
55
6+ Persistent<Function> MyObject::constructor;
7+
68MyObject::MyObject () {};
79MyObject::~MyObject () {};
810
@@ -12,28 +14,49 @@ void MyObject::Init(Handle<Object> target) {
1214 tpl->SetClassName (String::NewSymbol (" MyObject" ));
1315 tpl->InstanceTemplate ()->SetInternalFieldCount (1 );
1416 // Prototype
15- tpl->PrototypeTemplate ()->Set (String::NewSymbol (" plusOne" ),
16- FunctionTemplate::New (PlusOne)->GetFunction ());
17+ NODE_SET_PROTOTYPE_METHOD (tpl, " value" , GetValue);
18+ NODE_SET_PROTOTYPE_METHOD (tpl, " plusOne" , PlusOne);
19+ NODE_SET_PROTOTYPE_METHOD (tpl, " multiply" , Multiply);
1720
18- Persistent<Function> constructor = Persistent<Function>::New (tpl->GetFunction ());
21+ constructor = Persistent<Function>::New (tpl->GetFunction ());
1922 target->Set (String::NewSymbol (" MyObject" ), constructor);
2023}
2124
2225Handle<Value> MyObject::New (const Arguments& args) {
2326 HandleScope scope;
2427
2528 MyObject* obj = new MyObject ();
26- obj->counter_ = args[0 ]->IsUndefined () ? 0 : args[0 ]->NumberValue ();
29+ obj->value_ = args[0 ]->IsUndefined () ? 0 : args[0 ]->NumberValue ();
2730 obj->Wrap (args.This ());
2831
2932 return args.This ();
3033}
3134
35+ Handle<Value> MyObject::GetValue (const Arguments& args) {
36+ HandleScope scope;
37+
38+ MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder ());
39+
40+ return scope.Close (Number::New (obj->value_ ));
41+ }
42+
3243Handle<Value> MyObject::PlusOne (const Arguments& args) {
3344 HandleScope scope;
3445
3546 MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This ());
36- obj->counter_ += 1 ;
47+ obj->value_ += 1 ;
48+
49+ return scope.Close (Number::New (obj->value_ ));
50+ }
51+
52+ Handle<Value> MyObject::Multiply (const Arguments& args) {
53+ HandleScope scope;
54+
55+ MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This ());
56+ double multiple = args[0 ]->IsUndefined () ? 1 : args[0 ]->NumberValue ();
57+
58+ const int argc = 1 ;
59+ Local<Value> argv[argc] = { Number::New (obj->value_ * multiple) };
3760
38- return scope.Close (Number::New (obj-> counter_ ));
61+ return scope.Close (constructor-> NewInstance (argc, argv ));
3962}
0 commit comments