1.繼承有什么作用?
繼承是指一個對象直接使用另一個對象是屬性和方法话浇。
作用:繼承可以使子類共享父類的屬性和方法扩灯。
繼承可以覆蓋或擴(kuò)展父類的屬性和方法别威。
2.有幾種常見創(chuàng)建對象的方式? 舉例說明?
1.簡單對象字面量
var obj1 = {};
2.工廠模式
function Person(name,age){
var obj = {
name: name,
age: age
}
return obj;
}
var Person1 = Person("Li",18);
var Person2 = Person("Xin",18);
3.構(gòu)造函數(shù)
function Person(name,age){
this.name = name;
this.age = age;
}
var Person1 = new Person("Yun",20);
4.原型+構(gòu)造函數(shù)
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
console.log("name is " + this.name)
}
var Person1 = new Person("Jing",24);
Person1.sayName();
3.下面兩種寫法有什么區(qū)別?
//方法1
function People(name, sex){
this.name = name;
this.sex = sex;
this.printName = function(){
console.log(this.name);
}
}
var p1 = new People('Li', 2)
//方法2
function Person(name, sex){
this.name = name;
this.sex = sex;
}
Person.prototype.printName = function(){
console.log(this.name);
}
var p1 = new Person('Yun', 27);
第一種:直接將對象的屬性和方法都創(chuàng)建在了構(gòu)造函數(shù)上,沒創(chuàng)建一個對象實(shí)例驴剔,都要重復(fù)創(chuàng)建該對象的方法省古,造成資源浪費(fèi),比較耗內(nèi)存丧失。
第二種:對象的屬性創(chuàng)建在了構(gòu)造函數(shù)上豺妓,而方法寫在了原型prototype上,實(shí)例對象可通過原型鏈直接調(diào)用該方法布讹,實(shí)現(xiàn)了方法共享琳拭,節(jié)省了內(nèi)存空間。
4.Object.create 有什么作用描验?兼容性如何白嘁?如何使用?
Object.create可以創(chuàng)建一個擁有指定原型和若干個指定屬性的對象膘流。
兼容性:IE9+,Chrome5+,Firfox4.0+,Opera11.60+,Safari5+絮缅。
使用方法:Object.craete(prototype,[])
function Person(name){
this.name = name;
}
Person.prototype.sayName = function(){
console.log("name is " + this.name);
}
function People(){
}
People.prototype = Object.create(Person.prototype);
var p1 = new Person("li");
5.hasOwnProperty有什么作用鲁沥? 如何使用?
作用:返回一個布爾值耕魄,判斷某個對象是否含有指定的自身屬性画恰,而非其原型鏈上繼承到的屬性。
語法:obj.hasOwnProperty(prop),prop為要檢測的屬性
p1.hasOwnProperty('age');
6.實(shí)現(xiàn)Object.create的 polyfill吸奴,如:(ps: 寫個 函數(shù)create允扇,實(shí)現(xiàn) Object.create 的功能)
function create(obj){
function temp(){};
if(typeof obj !== 'object'){
console.log('error')
} else {
temp.prototype = obj;
var newTemp = new temp();
return newTemp;
}
}
var obj = {a: 1, b:2};
var obj2 = create(obj);
console.log(obj2.a); //1
7.如下代碼中call的作用是什么?
function Person(name, sex){
this.name = name;
this.sex = sex;
}
function Male(name, sex, age){
Person.call(this, name, sex); //call的作用,在Male作用域中調(diào)用Person则奥,使Male能夠執(zhí)行Person函數(shù)考润。
this.age = age;
}
8.實(shí)現(xiàn)繼承
function Person(name, sex){
this.name = name;
this.sex = sex;
}
Person.prototype.getName = function(){
console.log('name is ' + this.name);
};
function Male(name, sex, age){
this.age = age;
Person.call(this,name, sex);
}
Male.prototype = Object.create(Person.prototype);
Male.prototype.constructor = Male;
Male.prototype.getAge = function(){
console.log('age is ' + this.age);
};
var ruoyu = new Male('ruoyu', '男', 27);
ruoyu.getAge();