052_Function对象
1. Function對象
1.1. Function類可以表示開發者定義的任何函數。
1.2. 使用Function()構造函數可用動態創建函數。
1.3. JavaScript函數實際上是功能完整的對象。
1.4. 語法
new Function ([arg1[, arg2[, ...argN]],] functionBody)1.5. 參數
1.5.1. arg1, arg2, ... argN被函數使用的參數的名稱。
1.5.2. functionBody一個含有包括函數定義的JavaScript語句的字符串。
1.6. 實例
function doAdd1(a, b) {return a + b; }var doAdd2 = new Function('a', 'b', 'return a + b;');1.7. 通過Function的方式創建函數, 有助于我們理解, 函數只不過是一種引用類型, 函數名是指向函數對象的變量。
1.8. 使用Function創建函數例子
1.8.1. 代碼
<!DOCTYPE html> <html lang="zh-CN"><head><meta charset="utf-8" /><title>Function對象</title></head><body><script type="text/javascript">function doAdd1(a, b) {return a + b;}var doAdd2 = new Function('a', 'b', 'return a + b;');document.write(doAdd1(8, 9) + '<br />');document.write(doAdd2(8, 9));</script></body> </html>1.8.2. 效果圖
1.9. 盡管可以使用Function構造函數創建函數, 但最好不要使用它, 因為用它定義函數比用傳統方式要慢得多。不過, 所有函數都應看作Function類的實例。
1.10. 函數名是指向函數的變量, 那么可以把函數作為參數傳遞給另一個函數:
function doAdd(a, b) {return a + b; }function doAddWrap(doAdd, a, b) {document.write('a = ' + a + '<br />');document.write('b = ' + b + '<br />');return doAdd(a, b); }1.11. 使用函數當作參數例子
1.11.1. 代碼
<!DOCTYPE html> <html lang="zh-CN"><head><meta charset="utf-8" /><title>函數參數</title></head><body><script type="text/javascript">function doAdd(a, b) {return a + b;}function doAddWrap(doAdd, a, b) {document.write('a = ' + a + '<br />');document.write('b = ' + b + '<br />');return doAdd(a, b);}document.write(doAddWrap(doAdd, 8, 9));</script></body> </html>1.11.2. 效果圖
2. Function對象屬性
3. length屬性
3.1. length屬性指明函數的形參個數。
3.2. length是函數對象的一個屬性值, 指該函數有多少個必須要傳入的參數, 即形參的個數。形參的數量不包括剩余參數個數, 僅包括第一個具有默認值之前的參數個數。
4. name屬性
4.1. name屬性返回一個函數聲明的名稱。
4.2. 使用new Function(...)構造器創建的函數名稱為anonymous(匿名)。
5. Function對象方法
6. apply()方法
6.1. apply()方法調用一個具有給定this值的函數, 以及以一個數組(或類數組對象)的形式提供的參數。
6.2. 語法
func.apply(thisArg, [argsArray])6.3. 參數
6.3.1. thisArg可選的。在func函數運行時使用的this值。請注意, this可能不是該方法看到的實際值: 如果這個函數處于非嚴格模式下, 則指定為null或undefined時會自動替換為指向全局對象, 原始值會被包裝。
6.3.2. argsArray可選的。一個數組或者類數組對象, 其中的數組元素將作為單獨的參數傳給func函數。如果該參數的值為null或 undefined, 則表示不需要傳入任何參數。
6.4. 本例調用person的fullName方法, 并用于person1:
var person = {fullName: function() {return this.firstName + " " + this.lastName;} } var person1 = {firstName:"Bill",lastName: "Gates", } person.fullName.apply(person1); // 將返回 "Bill Gates"6.5. 帶參數的apply()方法:
var person = {fullName: function(city, country) {return this.firstName + " " + this.lastName + "," + city + "," + country;} } var person1 = {firstName:"Bill",lastName: "Gates" } person.fullName.apply(person1, ["Seattle", "USA"]);7. call()方法
7.1. call()方法使用一個指定的this值和單獨給出的一個或多個參數來調用一個函數。
7.2. 語法
function.call(thisArg, arg1, arg2, ...)7.3. 參數
7.3.1. thisArg可選的。在function函數運行時使用的this值。請注意, this可能不是該方法看到的實際值: 如果這個函數處于非嚴格模式下, 則指定為null或undefined時會自動替換為指向全局對象, 原始值會被包裝。
7.3.2. arg1, arg2, ...指定的參數列表。
7.4. apply()方法與call()方法非常相似:
var person = {fullName: function() {return this.firstName + " " + this.lastName;} } var person1 = {firstName: "Bill",lastName: "Gates", } person.fullName.call(person1); // 將返回 "Bill Gates"7.5. call()和apply()之間的區別:
7.5.1. call()方法分別接受參數。
7.5.2. apply()方法接受數組形式的參數。
8. bind()方法
8.1. bind()方法創建一個新的函數, 在bind()被調用時, 這個新函數的this被指定為bind()的第一個參數, 而其余參數將作為新函數的參數, 供調用時使用。
8.2. 語法
function.bind(thisArg[, arg1[, arg2[, ...]]])8.3. 參數
8.3.1. thisArg調用綁定函數時作為this參數傳遞給目標函數的值。如果使用new運算符構造綁定函數, 則忽略該值。當使用bind在setTimeout中創建一個函數(作為回調提供)時, 作為thisArg傳遞的任何原始值都將轉換為 object。如果bind函數的參數列表為空, 或者thisArg是null或undefined, 執行作用域的this將被視為新函數的thisArg。
8.3.2. arg1, arg2, ...當目標函數被調用時, 被預置入綁定函數的參數列表中的參數。
9. toString()方法
9.1. toString()方法返回一個表示當前函數源代碼的字符串。
9.2. 語法
function.toString()9.3. Function對象覆蓋了從Object繼承來的toString方法。對于用戶定義的Function對象, toString方法返回一個字符串, 其中包含用于定義函數的源文本段。
9.4. 如果是在內置函數或由Function.prototype.bind返回的函數上調用toString(), 則toString()返回原生代碼字符串。
9.5. 若是在由Function構造器生成的函數上調用toString(), 則toString()返回創建后的函數源碼, 包括形參和函數體, 函數名為"anonymous"。
10. 例子
10.1. 代碼
<!DOCTYPE html> <html lang="zh-CN"><head><meta charset="utf-8" /><title>Function對象</title></head><body><script type="text/javascript">function doPlus(){}function doMinus(param1, param2){} function doMultiply(param1, param2, param3 = 0, param4, param5){}function doDivision(...args){}var sum = new Function('a', 'b', 'return a + b;');var remainder = new Function();document.write(doPlus + ', ' + doPlus.constructor + ', ' + (doPlus.constructor === Function) + '<br />');document.write(doMinus + ', ' + doMinus.constructor + ', ' + (doMinus.constructor === Function) + '<br />');document.write(doMultiply + ', ' + doMultiply.constructor + ', ' + (doMultiply.constructor === Function) + '<br />');document.write(doDivision + ', ' + doDivision.constructor + ', ' + (doDivision.constructor === Function) + '<br />');document.write(sum + ', ' + sum.constructor + ', ' + (sum.constructor === Function) + '<br />');document.write(remainder + ', ' + remainder.constructor + ', ' + (remainder.constructor === Function) + '<br />');document.write(Function + ', ' + Function.constructor + ', ' + (Function.constructor === Function) + '<hr />');document.write('doPlus函數的形參個數: ' + doPlus.length + '<br />');document.write('doMinus函數的形參個數: ' + doMinus.length + '<br />');document.write('doMultiply函數的形參個數: ' + doMultiply.length + '<br />');document.write('doDivision函數的形參個數: ' + doDivision.length + '<br />');document.write('sum函數的形參個數: ' + sum.length + '<br />');document.write('remainder函數的形參個數: ' + remainder.length + '<hr />');document.write('doPlus.name = ' + doPlus.name + '<br />');document.write('doMinus.name = ' + doMinus.name + '<br />');document.write('doMultiply.name = ' + doMultiply.name + '<br />');document.write('doDivision.name = ' + doDivision.name + '<br />');document.write('sum.name = ' + sum.name + '<br />');document.write('remainder.name = ' + remainder.name + '<br />');document.write('Function.name = ' + Function.name + '<hr />');var module = {x: 42,getX: function(){return this.x;}};document.write('x = ' + module.getX() + '<br />');var unboundGetX = module.getX;document.write('x = ' + unboundGetX() + '<br />');var boundGetX = unboundGetX.bind(module);document.write('unboundGetX == boundGetX: ' + (unboundGetX == boundGetX) + '<br />');document.write('x = ' + boundGetX() + '<hr />');document.write(module.getX.toString() + '<br />');document.write(sum.toString() + '<br />');document.write(Math.max.toString() + '<br />');document.write(boundGetX.toString() + '<hr />');var person = {fullName: function() {return this.firstName + " " + this.lastName;}}var person1 = {firstName:"Bill",lastName: "Gates",}document.write(person.fullName.call(person1) + '<br />');document.write(person.fullName.apply(person1) + '<br />');document.write(Math.max.apply(null, [1,2,3]) + '<br />');var data = '123456';function display() {document.write('data value is ' + this.data + '<br />');}// 沒有參數的call和applay使用的是全局對象Windowdisplay.call();display.apply();function ClassPeople(firstName, lastName){this.firstName = firstName;this.lastName = lastName;document.write('<hr />firstName = ' + firstName + ', lastName = ' + lastName + '<br />');}var cp = ClassPeople.bind();new cp('zhang', 'san');function fn(){document.body.appendChild(document.createTextNode('this = ' + this + ', typeof(this) = ' + typeof(this)));}var nfn = fn.bind(1);setTimeout(nfn, 1000);</script></body> </html>10.2. 效果圖
11. 模擬call、apply和bind方法例子
11.1. 代碼
<!DOCTYPE html> <html><head><title>模擬call、apply和bind方法</title></head><body><script type="text/javascript">Function.prototype.mycall = function(context){var args = Array.prototype.slice.call(arguments, 1);context.__proto__.fn = this;// 可變參數context.fn(...args);context.__proto__.fn = undefined;};Function.prototype.myapply = function(context, args){if(!(args instanceof Array)){throw new Error("Uncaught TypeError: CreateListFromArrayLike called on non-object");}context.__proto__.fn = this;context.fn(...args);context.__proto__.fn = undefined;};Function.prototype.mybind = function(context){var fn = this, firsts = Array.prototype.slice.call(arguments, 1);return function(){return fn.apply(context, firsts.concat(Array.prototype.slice.call(arguments)));};};Function.prototype.mybind2 = function(context){var fn = this, afters = Array.prototype.slice.call(arguments, 1);return function(){return fn.apply(context, Array.prototype.slice.call(arguments).concat(afters));};};var obj = {fullName: function(city, country){document.write(this.firstName + this.lastName + "," + city + "," + country + "<br />");}};function ClassPeople(firstName, lastName){this.firstName = firstName;this.lastName = lastName;}var zs = new ClassPeople('zhang', 'san');obj.fullName.call(zs, 'luoyang', 'zh');obj.fullName.mycall(zs, 'luoyang', 'zh');document.write("<hr />");var ls = new ClassPeople('li', 'si');obj.fullName.apply(ls, ['shanghai', 'zh']);obj.fullName.myapply(ls, ['shanghai', 'zh']);document.write("<hr />");var ww = new ClassPeople('wang', 'wu');obj.fullName.bind(ww, 'xianggang')('zh');obj.fullName.mybind(ww, 'xianggang')('zh');obj.fullName.mybind2(ww, 'zh')('xianggang');</script></body> </html>?11.2. 效果圖
總結
以上是生活随笔為你收集整理的052_Function对象的全部內容,希望文章能夠幫你解決所遇到的問題。