js知识点整理 四

JS面向对象

function Person(name,sex,age){

        this.name = name;

        this.sex = sex;

        this.age = age;

        this.info=function(){

                console.log(this.name+this.sex+this.age);

        }

}

定义了一个类

this关键字的使用

this在对象中时是指当前对象,如果在全局范围值window对象

类即是函数,函数也可以当成类型处理

function Person(name,age,sex){

       this.age = age;

       this.name = name;

       this.sex = sex;

       this.say = function(){

              console.log(this.name)

       }

}

Person(‘aaa’,12,‘男’)   //这个只是单纯的调用,方法走到里面的时候this代表的是window

var p = new Person(‘aaa’,12,’男’)       //这里的p就是一个对象,这里面的this是指p对象本身

apply() 函数的作用:改变方法的调用者

p.say.apply() 这种调用方式的主体是window,因为apply()默认无参数就是window对象,say方法里面的this就是window对象

p.say.apply(p) 这种调用方就是p自己了,say方法里面的this就是p对象

call()函数的作用和apply()函数的作用基本一致,区别在于调用的参数不一致,call(obj,argv1,argv2…) ,apply(obj ,[ argv1,argv2…])


猜你喜欢

转载自blog.csdn.net/livelse/article/details/80883773