-1

我有这个 Javascript 类,想在这个类的属性中添加某种函数(如原型)。

function theUploader(virtualField)
{
     var self = this;
   //self.v = virtualField;
     self.v = (function(){return self.v; this.clear = function(){self.v = '';}})()
     self.v.prototype = function clear() {
       self.v = '';
     }
}

我试过这些台词。我找不到定义这种东西的正确方法。我想这样称呼它

var temp = new theUploader('smart');
temp.v.clear();

有人用 jsaon 指导我。但仍在努力

4

2 回答 2

0

The problem(s) with this line:

self.v = (function(){return self.v; this.clear = function(){self.v = '';}})()

...would be more obvious if you split it out over several lines:

self.v = (function(){
             return self.v;
             this.clear = function(){
                             self.v = '';
             }
         })()

It's an immediately invoked function expression which returns on its first line, so it never gets to the this.clear = ... line. The value returned, self.v, will be undefined at that point, which means the self.v property you assign that value to will also be undefined, which means then on this line:

self.v.prototype = function clear() {

...you'll get an error TypeError: Cannot set property 'prototype' of undefined.

It's a bit hard to tell exactly what you're trying to do given the confusion in your theUploader() function, but given that you said you want to be able to do this:

var temp = new theUploader('smart');
temp.v.clear();

Then you need to create a .v property that is itself an object that has a .clear() method, so:

function theUploader(virtualField)
{
     var self = this;
     self.v = {};                                // create a v property that is an object
     self.v.clear = function(){self.v = '';};    // add a method to v
}

...would do it. Or you could define the clear function directly in the object literal:

     self.v = {
        clear : function(){self.v = '';}
     };

(Either way it doesn't really make sense to me that calling self.v.clear() would actually overwrite the .v property with an empty string, but if that's what you want this is how you could do it.)

于 2013-09-01T07:16:38.567 回答
0
self.v.prototype = function clear() {
   self.v = '';
}

应该

self.v.clear = function() {
    self.v = '';
}
于 2013-09-01T06:34:44.177 回答