您的位置:首页 > Web前端 > JavaScript

JavaScript个人笔记:面向对象设计二(继承)

2016-10-09 16:57 344 查看
一:功能函数及构造器函数

功能函数:a)通过调用功能函数,会在堆中动态创建一块空间闭包,执行完毕后把结果return出去,空间自动回收。b)功能函数注重的是函数的功能和结果。

function person(){
return '小王';
}
var res = person();


构造器函数:a)new关键字代表的是动态的开辟一块内存。
b)空间,并且把这块空间的内存地址返回出去,我们的目标其实就是操作这块新的内存


function Person(name){
this.name = name;
}
Person.prototype = {
eat : function(){
console.log('吃');
}
}
var p = new Person('小王'):
p.eat();


二、构造函数的继承

//面向对象的编程指的是组织业务逻辑的代码操作的都是对象

Object.prototype.extends = function(func,action){
for(var prop in func.prototype ){
this.prototype[prop] = func.prototype[prop];
}
for(var prop in action){
this.prototype[prop] = action[prop];
}
}
function Person(name){
this.name = name;
}
Person.prototype = {
getHand : function(person){
console.log(this.name+"牵着"+person.name);
},
eat:function(rice){
console.log(this.name+"正在吃"+rice.name+"..");
},
study:function(){
console.log(this.name+"学习");
},
wtv:function(tv){
console.log(this.name+"看"+tv);
}

}
function Son(name){
this.name = name;
}
Son.extends(Person);
function Father(name){
this.name = name;
}
Father.extends(Person,{
carry:function(person){
console.log(this.name+"背着"+person.name+"回家");
}
})
function Mother(name){
this.name = name;
}
Mother.extends(Person,{
sleep : function(person){
console.log(this.name+"抱着"+person.name+"睡觉");
}
})
function Rice(name){
this.name = name;
}
var f = new Father('小头爸爸');
var s = new Son('大头儿子');
var m = new Mother('围裙妈妈');
f.getHand(s);
s.eat(new Rice('蛋炒饭'));
f.carry(s);
s.study();
s.wtv('黑猫警长');
f.wtv('足球');
m.sleep(s);


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: