this

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
<!--
    1.this指向(在函数种使用的this,实际上是不知道this指向谁,只能通过以下的调用才可以知道this的指向)
      1.通过new的方式(new a()):这里的this指向:创建新的对象
      2.通过直接调用的方式( a() ):这里this指向:windows,会造成无法获取到this指向的内容
      3.通过调用对象的方式:(  obj.met()  ):这里this指向前面的对象
      4.强制改变this指向(call/apply:他们区别:apply是通过数组去传参,而call是一个一个传参)
     -->
</head>
<body>
    <script>
// 1、
//         function a(){
//             this.a = 0;
//             console.log(this.a)
//         }
//     new a()
//2、
    //     function a(){
    //         console.log(this)
    //     }
    // a()

//3.
//  var obj = {
//     a : 1,
//     b : 2,
//     met : function(){
//             console.log(this)
//     },
//     c : {
//         d : function() {
//             console.log(this)
//         },
//         e : function(){
           
//         }
//     }
//  }
//  obj.met()

//4.call/apply:他们区别:apply是通过数组去传参,而call是一个一个传参
// function a(a,b){
//     console.log(this)
// }
// var arr = [1,2]
// a.call(arr)
// var arr1 = [3,4]
// a.apply(arr1)


//1.练习题:在sayhei里打印name和age
    // var person ={
    //     name : 'wsx',
    //     age : 19,
    //     sayhei : function(){
    //         //在sayhei里打印name和age
    //         console.log(this.name,this.age)
    //     }
    // }
    // person.sayhei()

//2.练习题:在所有的对象添加print,打印对象键值对
Object.prototype.print = function(){
    for(var key in this){
        //hasOwnProperty = 隐藏原型上的属性
        //if判断:this=a,b下面的方法,判断a,b下面方法是否包含print属性,将包含的执行以下语句,如果不包含则隐藏
        if(this.hasOwnProperty(key)){
            console.log(key,this[key])
        }
    }
}

     var a = {
        name : 'wsx',
        age : 19
     }
     var b = {
        name : 'wsx',
        age : 20
     }
a.print()



    //第三题:在不使用new以及不更改user函数的情况下输出姓名
    // function User(firatName,lastName){
    //      this.firatName = firatName;
    //      this.lastName = lastName;
    //      this.fullName = firatName+lastName
    // }
    // var user = {}
    // User.call(user,'l','ws')
    // console.log(user)

    </script>
</body>
</html>

posted on 2023-04-05 22:36  爱前端的小魏  阅读(74)  评论(0编辑  收藏  举报

导航