前端经典面试题js面向对象
1、什么是面向对象
面向对象就是用函数来封装一些特定的属性和方法,用来使用
2、使用方法
1)创建函数
function animal(cat,dog) {
this.cat = cat;
this.dog = dog;
console.log(cat,dog);
console.log(this)
this.fly = function () {
alert("aaa")
}
}
2)函数以构造函数的调用
var anim = new animal("加菲猫","京巴");//new一个animal的对象,名叫anim
anim.cat = "a"; //为实例anim的属性cat重新赋值为a
anim.fly(); //调用fly()方法
3对象的继承
function animal2(cat,dog) {
//call可以传递一个参数列表
animal.call(this,cat,dog); //为animal2继承animal中的属性和方法
//apply需要一个数组来放传递列表
animal.apply(this,[cat,dog]) //和call功能一样,
}
4、原型和原型链
原型:prototype,相当于一个公共区域,可以向它添加属性和方法
1、我们每创建一个函数,解析器都会向函数中添加一个prototype的属性,这个属性对应一个对象,这个对象就是原型对象
2、通过构造函数调用的函数,会包含一个隐函属性,也指向函数的原型对象,可以使用__proto__查看
function myclass() {}
//myclass会默认添有一个prototype属性
//通过构造函数的形式调用会有一个隐含属性__proto
var mc = new myclass();
console.log(myclass.prototype==mc.__proto__)//true,都指向同一个原型对象
3.在原型对象中添加属性和方法
myclass.prototype.a = 123;//向原型对象中添加属性a
mc.a; mc中没有就会向他的上一级寻找,有就用自己的,没有就向上找