繼承有什么作用?
- 得到一個(gè)類的屬性
- 得到一個(gè)類的方法
有幾種常見(jiàn)創(chuàng)建對(duì)象的方式? 舉例說(shuō)明?
直接賦值
var obj={};
工廠模式
function createCake(name){
var obj={
name:name,
sayName:function(){
console.log('我是:'+name)
}
}
return obj;
}
var cake1= createCake('草莓蛋糕')
缺點(diǎn)是無(wú)法得到對(duì)象類型
- 構(gòu)造函數(shù)模式
function createCake(name){
this.name=name;
this.sayName=function(){
console.log('我是:'+this.name);
}
}
var cake1= new createCake('草莓蛋糕')
- 原型方式
function createCake(name){
this.name=name;
}
createCake.prototype.sayName=function(){
console.log('我是:'+this.name);
}
var cake1= new createCake('草莓蛋糕')
下面兩種寫法有什么區(qū)別?
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);
方法一是構(gòu)造函數(shù)模式,方法二是原型模式侦锯。方法二算是方法一的一種改進(jìn),把共有的屬性放在了原型當(dāng)中骂删,節(jié)省空間。
Object.create 有什么作用?兼容性如何宁玫?如何使用粗恢?
Object.create
創(chuàng)建一個(gè)擁有指定原型和若高個(gè)指定屬性的對(duì)象
ES5新特性,需要IE9以上版本
hasOwnProperty有什么作用欧瘪? 如何使用适滓?
可以判斷一個(gè)對(duì)象是否包含自定義屬性而不是原型鏈上的屬性,hasOwnProperty
是JS中唯一一個(gè)處理屬性但是不查找原型鏈的函數(shù)恋追。
實(shí)現(xiàn)Object.create的 polyfill,如:(ps: 寫個(gè) 函數(shù)create,實(shí)現(xiàn) Object.create 的功能)
var obj = {a: 1, b:2};
var obj2 = create(obj);
console.log(obj2.a); //1
if (typeof Object.create != 'function'){
Obj.create = (function(){
function Temp() {}
var hasOwn = Object.prototype.hasOwnProperty;
return function(proto){
if (typeof proto != 'object'){
throw TypeError('Object prototype may only be an Object or null');
}
Temp.prototype = proto;
var obj = new Temp();
Temp.prototype = null;
if (arguments.length > 1){
var Properties = Object(arguments[1]);
for (var prop in Properties){
if (hasOwn.call(Properties, prop)) {
obj[prop] = Properties[prop];
}
}
}
return obj;
};
})();
}
如下代碼中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;
}
改變this的指向罚屋,把環(huán)境改變到Male的環(huán)境內(nèi)苦囱,實(shí)現(xiàn)繼承。
補(bǔ)全代碼脾猛,實(shí)現(xiàn)繼承
function Person(name, sex){
// todo ...
}
Person.prototype.getName = function(){
// todo ...
};
function Male(name, sex, age){
//todo ...
}
//todo ...
Male.prototype.getAge = function(){
//todo ...
};
var ruoyu = new Male('若愚', '男', 27);
ruoyu.printName();
function inhert(superType,subType){
var _prototype = Object.create(superType.prototype);
_prototype.constructor=subType;
subType.prototype=_prototype;
}
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(name,sex);
this.age=age;
}
inhert(Person,Male);
Male.prototype.getAge=function(){
console.log(this.age);
}