JavaScript中的函数详解

函数中this的指向

    * 普通函数中this的指向----->window
    * 构造函数中this的指向----->实例对象
    * 对象.方法中this的指向----->当前的实例对象
    * 定时器方法中this的指向----->window
    * 原型对象中方法的指向----->当前的实例对象
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    //BOM中顶级对象是window,浏览器中所有的东西都是window的;
    //普通函数
    function person() {
    console.log(this);
    }
    person();//window

    //构造函数
    function Person() {
        console.log(this);//Person
        this.play=function () {
            console.log("人在广东已经漂泊十年");
            console.log(this);//Person
        };
    }
    var person=new Person();//window
    //对象.方法中的this
    person.play();
    //原型中的方法
    Person.prototype.eat = function () {
        console.log(this);//Person
    };

    //定时器中的this
    setInterval(function () {
        console.log(this);//window
    }, 1000);
</script>
</body>
</html>

函数也是对象

    * 函数是对象,对象不一定是函数
    * 对象中__proto__原型,函数中有prototype原型
    * 如果一个东西里面竟有__proto__,又有prototype,那么他既是函数也是对象
    * 所有的函数实际上都是通过Function的构造函数创建出来的实例对象
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    function Person() {

    }
    console.dir(Person);//既是函数也是对象
    console.dir(Math);//对象
    function F1() {

    }
    console.dir(F1);//里面有__proto__
    console.log(F1.__proto__==Function.prototype);//true
</script>
</body>
</html>

数组的函数调用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    //数组中可以存储任意类型的数据
    var arr=[
        function () {
        console.log("see");
        },
        function () {
            console.log("you");
        },
        function () {
            console.log("again");
        }
    ]
    arr.forEach(function (element) {
        element();
    })
</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值