首页 > 其他 > 详细

面向对象基本语法

时间:2019-05-23 16:11:06      阅读:104      评论:0      收藏:0      [点我收藏+]

Ctrl + G

        <script type="text/javascript">
        
//      面向对象编程
//      
//      对象呢?
//      
//      创建对象
//          var obj = {}
//          var obj2 = new Object();
//      构造函数
//      人
        var 甲 = {
            name:"甲",
            age:16,
            sex:1,
            say:function(){
                console.log(`${this.name}-${this.age}-${this.sex}`)
            }
        }
        console.log(甲)
        console.log(甲.name)
        
//      工厂模式:原料,加工,出厂
//      function createPeople(n,a,s){
//          var obj = {}
//          obj.name = n,
//          obj.age = a,
//          obj.sex = s,
//          obj.say = function(){
//              console.log(`${this.name}-${this.age}-${this.sex}`)
//          }
//          return obj;
//      }
//      var a = createPeople("甲",16,1)
//      var b = createPeople("乙",18,0)
//      a.say()
//      b.say()
//      a.skill = "特殊技能"
//      console.log(a)
//      console.log(b)
        
//      js提供的新的工厂模式的写法
        // 构造(自定义)函数,让它变成对象
        function CreatePeo(n,a,s){      //原料

            // console.log(this)

            //给将来的对象加属性,出来了this

            // this指向将来new出来的对象(实例)

            this.abc = n;   
            this.age = a;
            this.sex = s;
            this.say = function(){
                console.log(`${this.abc}-${this.age}-${this.sex}`)
            }
        }
        CreatePeo()     //大驼峰

        new CreatePeo()//让它变成对象,new出厂

        let a = new CreatePeo("zhangsan",16,1); //new出厂

        let b = new CreatePeo("lisi",18,0); //new出厂

        a.say()             //zhangsan-16-1

        b.say()             //lisi-18-0

        a.show = "hahahah"  //给加属性show

        console.log(a)      //CreatePeo?{abc: "zhangsan", age: 16, sex: 1, say: ?, show: "hahahah"}

        console.log(b)      //CreatePeo?{abc: "lisi", age: 18, sex: 0, say: ?}
        
        console.log(abc)    //undefined 作为window的全局变量来执行了,createPeo(),此时this指向window,所有new时候,函数首字母大写

        console.log(age)    //undefined

        console.log(sex)    //undefined

        console.log(say)  //? (){
                //console.log(`${this.abc}-${this.age}-$///{this.sex}`)
                    //}
        
        
//      如果一个函数被new执行了,那么这个函数会默认有一个返回值,这个返回值是函数同名对象
//      在这个被new的函数中,this已经不是原本的this了,是将来被new出来的对象
        
        
//      this谁执行了所在的函数,this就是谁
//      但是
//      如果this遇到new
//      this就被new掰弯了,指向了new出来的对象
        
        
    </script>

面向对象基本语法

原文:https://www.cnblogs.com/sansancn/p/10912375.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!