繼承有什么作用?
繼承是指一個(gè)對(duì)象可以使用另一個(gè)對(duì)象的屬性和方法
可以使子類共享父類的屬性和方法,可以覆蓋和擴(kuò)展父類的屬性和方法,節(jié)省了代碼量,減少了內(nèi)存的使用违帆。
下面兩種寫(xiě)法有什么區(qū)別?
//方法1
function People(name, sex){
this.name = name;
this.sex = sex;
this.printName = function(){
console.log(this.name);
}
}
var p1 = new People('饑人谷', 2)
//方法2
function Person(name, sex){
this.name = name;
this.sex = sex;
}
Person.prototype.printName = function(){
console.log(this.name);
}
var p1 = new Person('若愚', 27);
區(qū)別:方法一函數(shù)所創(chuàng)建的方法在對(duì)象內(nèi)部,方法二函數(shù)所創(chuàng)建的方法在prototye原型上
方法一再創(chuàng)建一個(gè)Person對(duì)象實(shí)例時(shí)需要再創(chuàng)建一個(gè)printName方法金蜀,占用新的內(nèi)存刷后。
而方法二printName方法寫(xiě)在原型上的畴,當(dāng)對(duì)象要使用該方法只需到原型鏈里調(diào)用就可以了,達(dá)到節(jié)省內(nèi)存的效果尝胆。
Object.create 有什么作用丧裁?兼容性如何?
Object.create()創(chuàng)建一個(gè)具有指定原型且可選擇性地包含指定屬性的對(duì)象
student.prototype=Object.create(Person.prototype)
兼容性.png
hasOwnProperty有什么作用含衔? 如何使用煎娇?
hasOwnPerperty是Object.prototype的一個(gè)方法,可以判斷一個(gè)對(duì)象是否包含自定義屬性而不是原型鏈上的屬性贪染,hasOwnProperty是JavaScript中唯一一個(gè)處理屬性但是不查找原型鏈的函數(shù)
m.hasOwnProperty('name'); // true
m.hasOwnProperty('printName'); // false
Male.prototype.hasOwnProperty('printAge'); // true
如下代碼中call的作用是什么?
function Person(name, sex){
this.name = name;
this.sex = sex;
}
function Male(name, sex, age){
Person.call(this, name, sex); //這里的 call 有什么作用
this.age = age;
}
這里call的作用是調(diào)用person函數(shù)缓呛,然后設(shè)置this對(duì)象為male,從而讓male函數(shù)可以調(diào)用person的屬性
補(bǔ)全代碼杭隙,實(shí)現(xiàn)繼承
function Person(name, sex){
this.name=name
this.sex=sex
}
Person.prototype.getName = function(){
console.log(this.name)
};
function Male(name, sex, age){
Person.call(this,name,sex)
this.age=age
}
Male.prototype = Object.create(Person.prototype)
Male.prototype.constructor=Male
Male.prototype.getAge = function(){
console.log(this.age)
};
var ruoyu = new Male('若愚', '男', 27);
ruoyu.getName();