javascript对象章节学习第二部分

1、类和成员的访问控制:使用this关键字或者prototype定义的属性和方法是公共成员。使用var关键字定义的成员为私有成员,不能为外部所访问。

2、创建子类方法

function Person(myName,myAge){
this.name = myName;
this.age = myAge;
this.showInfo = function(){
return"我的年龄是"+this.age;
}
}
function Child(){}
Child.prototype = new Person();
var child_1 = new Child();
child_1.name="jane";
child_1.age = 20;
console.log(child_1.showInfo());

3、使用基类的构造器方法

function Person(myName,myAge){
this.name = myName;
this.age = myAge;
this.showInfo = function(){
return"我的年龄是"+this.age;
}
}
function Child(myName,myAge){
this.$super = Person;
this.$super(myName,myAge);
}
Child.prototype = new Person();
var child_1 = new Child("jane",8);
child_1.showInfo();

使用$super访问基类的完整应用

Object.prototype.$super=function(){
var result;
try{
//首先获取基类的构造器,将它保存在变量result中
result = eval(this.constructor).prototype.constructor;
//调用基类的构造器方法
result.apply(this,arguments);
}
catch(err){
//如果不是内建类或者自定义类,或者不在构造器中调用该方法,那么抛出错误
throw new Error("only can be used in constructor!");
}
return result;
}




function Person(){
if(arguments.length>2){
throw new Error("Two arguments only can be allowed");
}
this.nickName = arguments[0];
this.age = arguments[1];
}
Person.prototype.showInfo = function(){
return ("嗨! 我的名字是"+this.nickName);
}
function Child(myName,myAge){
this.$super(myName,myAge);
}
Child.prototype = new Person();
var child_1 = new Child("jane",8);
child_1.showInfo();

4、静态成员、静态类

方法:只需将属性或者方法赋给类本身

function Person(myName,myAge){
this.name = myName;
this.age = myAge;
}
Person.showInfo = function(){
return("嗨,我的性别是"+this.sex);
}
Person.sex = "男";

静态方法中,只能访问静态属性sex

静态成员不能被继承,但是可以传播。

5、覆载

方法覆载,在子类重定义一个同名的方法,属性覆载,需要使用get和set存取器定义属性。

6、原型链本质论

每一个类都有一个prototype属性,这是一个静态属性。该属性值包含了标识该类的一个对象,这个对象成为原型对象。

在原型对象上定义了一些内部属性,用于描述该类,其中包括该类的基类的信息。通过该信息,javascript解释引擎就能知道该类的基类。该描述基类信息的内部属性成为【Prototype】,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值