OOP继承(Js)

2017-04-01  本文已影响0人  jasmine_jing
//基于原型的继承
/*function Foo(){
    this.y =2;
    }
typeof Foo.prototype;//"object"
Foo.prototype.x = 1;
var obj = new Foo();
console.log(obj.x); //1
console.log(obj.y); //2*/

/*function Person(name,age){
    this.name = name;
    this.age = age;
    }
Person.prototype.hi = function(){
    console.log("Hi,my name is"+ this.name+", I am"+this.age+" years old now.");
    };
Person.prototype.legs_num = 2;
Person.prototype.arms_num = 2;
Person.prototype.walk =function(){
    console.log(this.name +"is walking...");
    };
function Student(name,age,className){
    Person.call(this,name,age);
    this.className = className;
    }   
        
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

Student.prototype.hi = function(){
    console.log("Hi,my name is " +this.name+", I am" +this.age +" years old now,and from " +this.className +".");
    }
    
Student.prototype.learn = function(subject){
    console.log(this.name +" is learning " +subject+" at " +this.className +".");
    }
var born = new Student('Bosn',23,'Class3');
born.hi();//Hi,my name is Bosn, I am23 years old now,and from Class3.
born.learn('English');//Bosn is learning English at Class3.
born.legs_num;
born.walk();//Bosnis walking...

Student.prototype.x =11;//赋值、添加时 影响已经实例过的对象
console.log(born.x);//11

Student.prototype={y:2};//直接修改赋值为新的对象时 对已经实例化过的对象没有影响,但是会影响 后续创建的实例 如下面的sunny 
console.log(born.y);//undefined
console.log(born.x);//11

var sunny = new Student('sunny',3,'Class lol');//再次实例一个新的对象
console.log(sunny.x);//undefined
console.log(sunny.y);//2*/

D@K{{WM43C04SFEKXYH0HJ7.png

![7M1J1U}$$N{]$@K(ENJY`YN.png](https://img.haomeiwen.com/i3167851/bc45bbd891271ce4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

YS8E1YJD45W$GQ$OPBIRCFU.png 8OYT9R1K~TIV(_F$R4V}9J7.png Paste_Image.png

实现继承的方法:

Paste_Image.png

OOP模拟重载

function Person(){
    var args = arguments;
    if(typeof args[0] ==='object' && args[0]){//防止参数为null 对象
        if(args[0].name){
            this.name = args[0].name;
        }
        if(args[0].age){
            this.age = args[0].age;
        }   
    }else{
        if(args[0]){
            this.name = args[0];
        }
        if(args[1]){
            this.age = args[1];
        }
    }
}
Person.prototype.toString = function(){
    return 'name ='+this.name+',age='+this.age;
}

var born = new Person('Born',23);
console.log(born.toString());//name =Born,age=23

var sunny = new Person({name:'Sunny',age:32});
console.log(sunny.toString());//name =Sunny,age=32
上一篇下一篇

猜你喜欢

热点阅读