javascript OOP

来源:互联网 发布:不属于网络群众路线 编辑:程序博客网 时间:2024/05/01 16:04

1、create object

Method1:

var obj = new Object();

obj.name = 'wilsom';

obj.age=24;

Method2:

var obj = {

name:'wilsom',    //注意逗号

age:24

}

Method3构造方法:

var Person = function(name,age){

this.name = name;

this.age = age;

toString:function(){

    return 'name:'+this.name+',age:'+this.age;

}

}

Method4带默认值的构造方法:

var Person = function(name,age){

this.name = name || 'Lijia';

this.age = age || 24;

}

2、继承extends

var Farther = function(lastName){

this.lastName= lastName;

this.getLastName=function(){

return this.lastName;

}

}

var Child=function(age){

this.age = age;

this.getAge=function(){

return this.lastName;

}

}

Child.prototype = new Farther('LI');  //继承

console.log(new Child().getLastName()); //输出LI

原创粉丝点击