JavaScript高级知识回顾

118 阅读1分钟

内置对象

数组对象

<body>
    <script>
        let arr = [2, 5, 1, 9, 6]

        console.log(arr.concat([1, 3, 5, 7, 2]))

        console.log(arr.reverse())

        console.log(arr.join('|'))

        let arr1 = arr.sort(function (a, b) {
            return a - b //从小到大
        })
        console.log(arr1)

        let arr2 = arr.sort(function (a, b) {
            return b - a //从大到小
        })
        console.log(arr2)


    </script>
</body>

字符串对象

<body>
    <script>
        let str = '我爱前端'

        console.log(str.indexOf('前端'))
        console.log(str.indexOf('前端人'))

        console.log(str.split('爱'))

        let stars = '★★★★★☆☆☆☆☆'
        console.log(stars.substr(0, 5))
        console.log(stars.substr(1, 5))
        console.log(stars.substr(2, 5))
        console.log(stars.substr(3, 5))
        console.log(stars.substr(4, 5))
        console.log(stars.substr(5, 5))

        let eng = 'abcdEFG'
        console.log(eng.toLocaleUpperCase())
        console.log(eng.toLocaleLowerCase())


    </script>
</body>

工厂函数

用于创建对象

构造函数

用于创建对象,加new关键字,return有时候有用(如果是引用类型,就会覆盖,如果不是,就没用),有时候没用。

原型对象

//为了避免空间浪费,所以把函数写外面,把function写外面
//再为了避免全局变量污染,所以把函数都放入一个对象里
//最后为了避免这个对象的全局变量污染(因为如果有不同的构造函数,你又得写不同的对象,去放函数)
//所以诞生了,【原型对象】
//原型对象是任何函数声明的时候,自动创建的
<body>
    <script>

        

        function Person(name, age) {
            //构造函数
            //造人

            this.name = name
            this.age = age
            //this.eat = eat
            //this.sleep = sleep
            //不能这么写

        }

        Person.prototype = {
            //原型对象
            //放函数

            eat: function () {
                console.log('吃饭')
            },
            sleep: function () {
                console.log('睡觉')
            }
        }

        let p1 = new Person('lhy', 21)
        //实例对象
        //创建一个具体的人p1
        //console.log(p1.name)
        //console.log(p1.age)
        //p1.eat()
        //p1.sleep()


        //构造函数、原型对象、实例对象【3者之间的关系】
        //3个属性

        //实例对象,调用构造函数的方法
        //就是直接调用就行,不需要写p1._proto_.eat(),直接写p1.eat()



        //console.log(Person.prototype)
        //console.log(p1.__proto__)
        //console.log(Person.prototype === p1.__proto__)




     
        console.log(Person)
        //console.dir(Person)

        console.log(p1.__proto__.constructor)
        console.log(p1.__proto__.constructor === Person)
     
    </script>
</body>