js对象

作者: Dxes | 来源:发表于2019-12-07 09:21 被阅读0次
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
        </head>
        <body>
        </body>
    </html>
    
    <script type="text/javascript">
        //1.对象的直接量
        /*
         {
            属性1:属性值1,
            属性2:属性值2,
            ....
         }
         */
        p1 = {
            name:'小明',
            age: 18,
            gender:'男'
        }
        p2 = {
            name:'张三',
            age: 20, 
            gender:'女'
        }
        
        //2.构造方法(相当于类)
        /*
         构造方法本质就是函数。
         
         语法:
         function 函数名/类名(参数列表){
            this.属性1 = 值1
            this.属性2 = 值2
            ...
            return this
         }
         
         构造方法的调用(创建对象): new 函数名()
         */
        function Person(name, age, gender='男'){
            //===对象属性====
            this.name = name
            this.age = age
            this.gender = gender
            
            //===对象方法====
            this.eat = function(food){
                console.log(this.name+'在吃'+food)
            }
            this.study = function(){
                console.log(this.name+'在学习')
            }
            
            return this
        }
        
        p3 = new Person('小红', 20)
        p4 = new Person('Tom', 30, '女')
        console.log(p1)
        console.log(p3)
        console.log(p4)
        
        //3.使用对象属性  - 查
        //对象.属性
        //对象[属性名]
        console.log(p1.name, p1['age'])
        console.log(p3.name, p3['age'])
        
        p3.eat('面条')
        p4.eat('面包')
        
        p4.study()
        
        //4.修改对象属性/添加对象属性
        //对象.属性 = 值     -   属性如果存在就是修改,属性不存在就是添加
        //对象[属性名] = 值   -   属性如果存在就是修改,属性不存在就是添加
        
        p3.id = '0001'
        console.log(p3)
        console.log(p3.id, p3['id'])
        
        p3['weight'] = 100
        console.log(p3)
        
        p3.name = '余婷'
        p3['age'] = 18
        console.log(p3)
        
        console.log(p4)
        
        //5.添加属性和方法
        /*
         类名.prototype.属性名 = 值    - 给指定的类添加属性和方法
         */
        Person.prototype.abc = 100
        console.log(p4.abc, p4['abc'])
        
        p5 = new Person('大黄', 3)
        console.log(p5.abc)
        
        
        String.prototype.ytToUpper = function(){
            //'a' <= char <= 'z'(python)  -> char >= 'a' && char <= 'z'
            tChar = this[0]
            if(tChar>='a' && tChar <= 'z'){
                return tChar.toUpperCase()+this.slice(1)
            }
            return this
        }
        
        str1 = 'abc'
        console.log(str1.ytToUpper())
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    </script>
    

    相关文章

      网友评论

          本文标题:js对象

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