Home > Web Front-end > JS Tutorial > body text

Detailed explanation of js class inheritance and prototype inheritance_javascript skills

WBOY
Release: 2016-05-16 15:06:05
Original
1413 people have browsed it

The example in this article shares with you the code related to js class inheritance and prototype inheritance for your reference. The specific content is as follows

1.js class inheritance

/* -- 类式继承 -- */
//先声明一个超类

function Person(name) {
this.name = name;
}
//给这个超类的原型对象上添加方法 getName 
Person.prototype.getName = function() {
return this.name;
}
//实例化这个超
var a = new Person('Darren1')
console.log(a.getName());//Darren1

//再声明类

function Programmer(name, sex) {
//这个类中要调用超类Person的构造函数,并将参数name传给它
Person.call(this, name);
this.sex = sex;
}
//这个子类的原型对象等于超类的实例
Programmer.prototype = new Person();
//因为子类的原型对象等于超类的实例,所以prototype.constructor这个方法也等于超类构造函数,你可以自己测试一下,如果没这一步,console.log(Programmer.prototype.constructor这个是Person超类的引用,所以要从新赋值为自己本身

console.log(Programmer.prototype.constructor);
/*function Person(name) {
this.name = name;
} */

Programmer.prototype.constructor = Programmer;
console.log(Programmer.prototype.constructor);

/*function Programmer(name, sex) {
Person.call(this, name);
this.sex = sex;
} 
*/
//子类本身添加了getSex 方法
Programmer.prototype.getSex = function() {
return this.sex;
}
//实例化这个子类
var _m = new Programmer('Darren2', 'male');
//自身的方法
console.log(_m.getSex());//male
//继承超类的方法
console.log(_m.getName());//Darren2
Copy after login

2.js prototypal inheritance

/* -- 原型式继承 -- */
//clone()函数用来创建新的类Person对象
var clone = function(obj) {
4
var _f = function() {};
//这句是原型式继承最核心的地方,函数的原型对象为对象字面量
_f.prototype = obj;
return new _f;
}
//先声明一个对象字面量
var Person = {
name: 'Darren',
getName: function() {
return this.name;
}
}
//不需要定义一个Person的子类,只要执行一次克隆即可
var Programmer = clone(Person);
//可以直接获得Person提供的默认值,也可以添加或者修改属性和方法
alert(Programmer.getName())
Programmer.name = 'Darren2'
alert(Programmer.getName())

//声明子类,执行一次克隆即可
var Someone = clone(Programmer);
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone in learning javascript programming.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!