javascript函数结构

时间:2011-02-16 09:18:53

标签: javascript

这是一个例子。

var x=5;
var y=x.multiplied(6); // return y=30;

如何在jsp>上创建类似.multiplied()函数的函数

功能结构是这样的

var1.doSomething(var2);

3 个答案:

答案 0 :(得分:2)


function myInteger( setVal ) {
 this.value = setVal;
}

myInteger.prototype.multiple( mult ) {
 return this.value * mult;
 // Or
 // return new myInteger( this.value * mult );
}

var x = new myInteger(5)
var y = x.multiple(6);

答案 1 :(得分:1)

需要像这样扩展Number对象..

var x = Number(5);
Number.prototype.multiplied = function(a) {return this * a;};

答案 2 :(得分:1)

如果你想创建类似乘法的fn,你需要在下面的例子中扩展特定类型的原型,你需要扩展一个Native类型,即

Number.prototype.multiplied = function(n){
    return this*n;
}

var x=5; //x is a Number
var y=x.multiplied(6); // return this*6 => this is x => that is 5 => 5*6 = 30;

一般来说,如果你有var1.doSomething(var2);而var1是一个对象,你可以用这种方式定义'方法'

function myObject(name){
   if(!(this instanceof myObject)){ // in the case you're missing 'new' when you declare a myObject instance
       return new myObject(name); 
   }
   this.name = name; //field
   this.doSomething = function(param){ //method
        alert('done '+param+' '+this.name);
   }
}
var var1 = new myObject('peter');
var var2 = "string";
var1.doSomething(var2); //alerts "done string peter"

var var3 = myObject('jean'); //don't need 'new'
var var4 = "homework";
var3.doSomething(var4); //alerts "done homework jean"

var1也可以是一般的'库',你可以用这种方式定义它:

var var1 = {
    doSomething : function(param){
       alert('done ' + param);
    }
}
//you don't need to instantiate a new object. You have a static library
var var2 = "mystring";
var1.doSomething(var2); //alerts "done mystring"