In-depth understanding of the JavaScript function series third

Source: Internet
Author: User
Tags instance method hasownproperty

Previous words

Functions are special objects in JavaScript and can have properties and methods, just as normal objects have properties and methods. You can even use the function () constructor to create a new function object. This article is an in-depth understanding of the third chapter of JavaScript function series--Properties and methods

Property

"Length Property"

Function series as described in the second article, the length property of the arguments object represents the number of arguments, and the length property of the function indicates the number of formal parameters

function add (x, y) {    console.log (arguments.length)//3    console.log (add.length);//2}add (n/a);

"Name Property"

The function defines a nonstandard Name property that allows access to the name specified by the given function, whose value is always equal to the identifier following the function keyword, and the Name property of the anonymous function is null

ie11-The browser is invalid, both output undefined//chrome has a problem processing the Name property of the anonymous function, it displays the function expression name functions fn () {};console.log (fn.name);//' FN ' var fn = function () {};console.log (Fn.name),//', in Chrome, ' fn ' var fn = function abc () {};console.log (fn.name);//' abc '    

[Note that the]name attribute has long been widely supported by the browser, but until ES6 writes it to the standard

ES6 has made some changes to the behavior of this property. If an anonymous function is assigned to a variable, the Name property of ES5 returns an empty string, and the Name property of ES6 returns the actual function name

var func1 = function () {};func1.name//es5: "  " Func1.name//es6: "Func1"

If you assign a named function to a variable, the Name property of both ES5 and ES6 returns the name of the named function.

var bar = function Baz () {};bar.name//es5: "Baz" Bar.name//es6: "Baz"

The function constructor returns a value of "anonymous" for the Name property

(new Function). Name//"Anonymous"

The function returned by bind, the Name property value is prefixed with "bound"

function foo () {};foo.bind ({}). Name//"Bound foo" (function () {}). bind ({}). Name//"Bound"

"Prototype Properties"

Each function has a prototype property that points to a reference to an object that is called a prototype object (prototype objects). Each function contains a different prototype object. When you use a function as a constructor, the newly created object inherits properties from the prototype object

function fn () {};var obj = new Fn;fn.prototype.a = 1;console.log (OBJ.A);//1

Method

"Apply () and call ()"

Each function contains two non-inherited methods: Apply () and call (). The purpose of both methods is to call a function in a specific scope, which is actually equal to the value of this object in the body of the function

To invoke the function f () in the method of object o, you can use call () and apply ()

F.call (o); f.apply (o);

Assuming that the M method does not exist in O, it is equivalent to:

O.M = f; The temporary method of storing F as O o.m (); Call it, do not pass in the parameter delete o.m; Remove the temporary method

The following is a practical example

Window.color = "Red"; var o = {color: "Blue"};function Saycolor () {    console.log (this.color);} Saycolor ();            Redsaycolor.call (this);   Redsaycolor.call (window); Redsaycolor.call (o);      Blue
Saycolor.call (o) is equivalent to: O.saycolor = Saycolor;o.saycolor ();   Bluedelete O.saycolor;

The Apply () method receives two parameters: one is the scope in which the function is run (or it can be said to be the parent object to invoke the function, which is the calling context, which is used in the body of the function to obtain a reference to it), and the other is the parameter array. Where the second parameter can be an instance of an array, or it can be a arguments object

function sum (NUM1, num2) {    return num1 + num2;} Because the scope of the running function is the global scope, this represents the Window object function callSum1 (NUM1, num2) {    return sum.apply (this, arguments);} function callSum2 (NUM1, num2) {    return sum.apply (this, [Num1, num2]);} Console.log (CALLSUM1 (10,10));//20console.log (CallSum2 (10,10));//20

The call () method has the same effect as the Apply () method, except that they differ only in the way they receive parameters. For the call () method, the first parameter is the this value does not change, changing the rest of the parameters are passed directly to the function. In other words, when using the call () method, the arguments passed to the function must be enumerated individually

function sum (NUM1, num2) {    return num1 + num2;} function Callsum (NUM1, num2) {    return Sum.call (this, NUM1, num2);} Console.log (Callsum (10,10));   20

Whether to use apply () or call () depends entirely on which function is most convenient for passing parameters. If you intend to pass in the arguments object directly, or if the containing function is also an array of first received, then using apply () is certainly more convenient; otherwise, choosing call () may be more appropriate

In non-strict mode, when you use the call () or apply () method of a function, null or undefined values are converted to global objects. In strict mode, the this value of the function is always the specified value

var color = ' red '; function Displaycolor () {    console.log (this.color);} Displaycolor.call (null);//red
var color = ' red '; function Displaycolor () {    ' use strict ';    Console.log (This.color);} Displaycolor.call (null);//typeerror:cannot Read property ' color ' of NULL

Application

Native method for "1" Call object

var obj = {};obj.hasownproperty (' toString ');//Falseobj.hasownproperty = function () {  return True;};o Bj.hasownproperty (' tostring ');//TrueObject.prototype.hasOwnProperty.call (obj, ' tostring ');//False

"2" finds the largest element of the array

JavaScript does not provide functions to find the largest elements of an array. Using the Apply method together with the Math.max method, you can return the largest element of an array

var a = [10, 2, 4, 15, 9]; Math.max.apply (null, a);//15

"3" Converts a class array object to a true array

Array.prototype.slice.apply ({0:1,length:1});//[1]

Or

[].prototype.slice.apply ({0:1,length:1});//[1]

"4" the object that binds the callback function

Since the Apply method (or call method) not only binds the object where the function executes, it also executes the function immediately, so the binding statement has to be written in a function body. A more concise approach is to use the Bind method described below

var o = {};o.f = function () {  Console.log (this = = = O);} var f = function () {  o.f.apply (o);}; $ (' #button '). On (' click ', f);

"Bind ()"

Bind () is a new method of ES5, and the main function of this method is to bind a function to an object

When you call the Bind () method on the function f () and pass in an object o as a parameter, this method returns a new function. Calling the new function as a function call will call the original function f () as O, and any arguments passed into the new function will be passed to the original function

Note ie8-Browser does not support

function f (y) {    return this.x + y;//This is the functions to be bound}var o = {x:1};//The object to be bound var g = F.bind (o);//Call O.F (x) g (2) by calling G (x);//3

Compatible code

function bind (f,o) {    if (f.bind) {        return f.bind (o);    } else{        return function () {            return f.apply (o,arguments);        }    }    

The bind () method not only binds a function to an object, it also comes with some other applications: arguments to the incoming bind () are bound to this, in addition to the first argument, and this accompanying application is a common functional programming technique, sometimes referred to as ' curry ' (currying)

var sum = function (x, y) {    return x+y;} var succ = Sum.bind (null,1); succ (2); 3,x binds to 1 and passes in 2 as argument y
function f (y,z) {    return this.x + y + z;} var g = F.bind ({x:1},2); G (3); 6,this.x bound to 1,y bound to 2,z bound to 3

Using the bind () method to Curry can split function parameters

function GetConfig (colors,size,otheroptions) {    console.log (colors,size,otheroptions);} var defaultconfig = Getconfig.bind (null, ' #c00 ', ' 1024x768 ');d efaultconfig (' 123 '),//' #c00 1024x768 123 ' Defaultconfig ( ' 456 ');//' #c00 1024x768 456 '

"ToString ()"

The ToString () instance method of the function returns a string of function code, while the static ToString () method returns a string similar to ' [native code] ' as the body of the function

function test () {    alert (1);//test}test.tostring ();/* "function test () {                    alert (1);//test                  }" */ Function.tostring ();//"function function () {[native code]}"

"toLocaleString ()"

The toLocaleString () method of the function and the ToString () method return the same result

function test () {    alert (1);//test}test.tolocalestring ();/* "function test () {                    alert (1);//test                  }" */ Function.tolocalestring ();//"function function () {[native code]}"

"ValueOf ()"

The valueof () method of the function returns the function itself

function test () {    alert (1);//test}test.valueof ();/*function test () {                    alert (1);//test                  }*/typeof Test.valueof ();//' function ' function.valueof ();//function () {[native code]}

Resources

"1" W3school-javascript Advanced Tutorial--function Object http://www.w3school.com.cn/js/
"2" Ruan one peak JavaScript standard reference Tutorial--function properties and methods http://javascript.ruanyifeng.com/grammar/
"3" JavaScript authoritative Guide (6th edition), chapter 8th function
"4" JavaScript Advanced Programming (3rd Edition), chapter 5th reference type
"5" JavaScript DOM Programming Art (2nd Edition), chapter 2nd JavaScript syntax
6 "javascript Statement essence" Chapter 4th function

In-depth understanding of the JavaScript function series third

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.