美文网首页
关于函数调用

关于函数调用

作者: 悸动无语 | 来源:发表于2018-04-28 18:08 被阅读0次

1.当调用函数时,除了传入在定义中显式声明的参数之外,同时还传入两个隐式参数,arguments 和 this。

①arguments参数是传入函数的所有参数的集合,具有length 属性,表示传入参数的个数,通过arguments参数还可以获取那些与函数形参不匹配的参数。在非严格模式下,arguments 对象是函数参数的别名,修改arguments对象会修改函数实参,可以通过严格模式避免修改函数实参。

②this 表示函数上下文,即与函数调用相关联的对象,函数的定义方式和调用方式决定this的取值

function example(parm1,parm1){

        console.log('this',this);

        console.log('arguments',arguments);

}

example(1,2)

2.函数的调用方式有4种:

①作为函数调用:example()

②作为方法调用:example.method()

③作为构造函数调用:new Example()

④通过apply('',[]) 与call('','','')

/ 1 函数模式调用 就是一个简单的函数调用. 函数名的前面没有任何引导内容.

function func() {

    console.log('函数模式');

}

func()

// 2 作为方法调用 方法一定是依附于一个对象, 将函数赋值给对象的一个属性, 那么就成为了方法

function myFunc0() {

    console.log('方法调用');

}

var methods={

myMethod:myFunc0

}

methods.myMethod()

// 3 构造函数调用

function myFunc1(){

console.log('构造函数')

}

var my = new myFunc1()

// 4 call apply

function myFunc2(){

console.log('call apply')

}

var test={};

myFunc2.apply(test,[]);

myFunc2.call(test,'');

3.函数的调用方式影响this的取值

①如果作为函数调用,在非严格模式下,this指向全局window对象;在严格模式下this指向 undefined

②作为方法调用,this通常指向调用的对象

③作为构造函数调用,this通常指向新创建的对象

④通过call apply 调用,this指向call apply 的第一个参数

// 1 非严格模式 函数模式调用

function func() {

    console.log('非严格模式-函数模式-this', this);

}

func()

// 严格模式 函数模式调用

function funcStrict() {

    "use strict";

    console.log('严格模式-函数模式-this', this);

}

funcStrict()

// 2 作为方法调用 

function myFunc0() {

    console.log('方法调用-this', this);

}

var methods = {

    myMethod: myFunc0

}

methods.myMethod()

// 3 构造函数调用

function myFunc1() {

    this.status = false;

    console.log('构造函数-this', this)

}

var my = new myFunc1()

// 4 call apply

function myFunc2() {

    var result = 0;

    for (var n = 0; n < arguments.length; n++) {

        this.result = arguments[n];

    }

    console.log('call apply-this', this)

}

var test = {};

myFunc2.apply(test, ['ex']);

myFunc2.call(test, 'ex');

4.箭头函数没有单独的this值,this创建时确定

5.所有函数均可使用bind方法,创建新函数,并绑定到bind方法传入的参数,被绑定的函数与原始函数具有一致的行为

https://www.cnblogs.com/jiaozhuo/p/5751002.html

document.getElementById('test2').onclick = function(color) {

    console.log(this)

    color = color || "#333333";

    this.style.color = color;

}.bind(document.getElementById('text'), "#ffcc33"); //黄色

相关文章

网友评论

      本文标题:关于函数调用

      本文链接:https://www.haomeiwen.com/subject/owfnlftx.html