Created
October 22, 2012 03:07
-
-
Save lyuehh/3929431 to your computer and use it in GitHub Desktop.
js func
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//方法调用模式 | |
var obj = { | |
val: 0, | |
inc: function(i) { | |
this.val += i; | |
} | |
}; | |
console.log(obj.val); | |
obj.inc(2); | |
obj.inc(2); | |
console.log(obj.val); | |
// 函数调用模式 | |
var add = function(a,b) { | |
return a + b; | |
}; | |
console.log(add(1,4)); | |
obj.double = function () { | |
var that = this; | |
var helper = function() { | |
that.val = add(that.val, that.val); | |
}; | |
helper(); | |
}; | |
obj.val = 5; | |
obj.double(); | |
console.log(obj.val); | |
// 构造器调用 | |
var Q = function(str) { | |
this.status = str; | |
}; | |
Q.prototype.getStatus = function() { | |
return this.status; | |
}; | |
var myQ = new Q('haha'); | |
console.log(myQ.getStatus()); | |
// //avoid this.. | |
// var yourQ = Q('haha'); | |
// console.log(yourQ.getStatus()); | |
// apply调用模式 | |
var array = [3,4]; | |
console.log(add.apply(null,array)); | |
console.log(add.call(null,3,4)); | |
var myStatus = { | |
status: 'ok..' | |
}; | |
console.log(Q.prototype.getStatus.apply(myStatus)); | |
|
Author
lyuehh
commented
Oct 23, 2012
Function.prototype.method = function(name, func) {
this.prototype[name] = func;
return this;
};
Array.method('reduce', function(f, value) {
for (var i = 0; i < this.length; i++) {
value = f(this[i], value);
};
return value;
});
var add = function(a, b) {
return a + b;
};
var mult = function(a, b) {
return a * b;
};
var data = [1, 2, 3, 4, 5];
var sum = data.reduce(add, 0);
var mult = data.reduce(mult, 1);
console.log('sum: ' + sum);
console.log('mult: ' + mult);
data.total = function() {
return this.reduce(add, 0);
};
console.log('total: ' + data.total());
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment