【说站】JavaScript有哪些继承的方法
2023-06-13 09:13:22 时间
JavaScript有哪些继承的方法
1、寄生式继承,基于某个对象创建一个对象,然后增强对象,返回对象。
function create(original){
// 通过调用函数创建一个新对象
var clone = object(original);
// 以某种方式增强对象
clone.sayHi = function(){
console.log('hi')
}
return clone;
}
var person = {
name: 'chen'
}
var person1 = create(person);
person1.sayHi();
2、原型链继承,将父类的实例作为子类的继承。
function Parent(){
this.name = 'parent'
}
Parent.prototype.sayName = function(){
return this.name
}
function Child(){
}
// 继承了Parent
Child.prototype = new Parent();
var child1=new Child();
child1.say();
3、组合继承,使用原型链继承共享的属性和方法。
通过借用构造函数继承实例属性。
function Parent(name){
this.name = name;
this.arr = [1,2,3]
}
Parent.prototype.sayName = function(){
console.log(this.name)
}
function Child(name,age){
// 继承属性
Parent.call(this, name)
this.age=age
}
// 继承方法
Child.prototype = new Parent()
Child.prototype.constructor = Child;
Child.prototype.sayAge = function(){
console.log(this.age)
}
var child1=new Child('chen',21);
child1.arr.push(4); //[1,2,3,4]
child1.sayName() // 'chen'
child1.sayAge() // 21
var child2=new Child('miao', 12)
child2.arr // [1,2,3]
child2.sayName() // "miao"
child2.sayAge() // 12
以上就是JavaScript继承的方法,希望对大家有所帮助。
相关文章
- RXJava原理_JavaScript的执行原理
- 用javascript分类刷leetcode---动态规划(图文视频讲解)
- JavaScript获取某年某月的最后一天详解编程语言
- javascript IOS 微信jssdk {“errMsg”:”config:fail”} 解决方案详解编程语言
- javascript tofixed四舍五入的方法详解编程语言
- 用javascript实现div可编辑的常见方法
- 用javascript取得传递参数的个数的代码
- javascript如何生成不重复的随机数
- javascript(js)join函数使用方法介绍
- JavaScript获得选中文本内容的方法
- JavaScript验证浏览器是否支持javascript的方法小结
- javascript继承实现方法
- JavaScript中函数声明优先于变量声明的实例分析
- javascript重复绑定事件造成的后果说明
- javaScript面向对象继承方法经典实现
- Javascript浮点运算的问题分析与解决方法
- javascript完美拖拽的实现方法
- 正则表达式语法规则及在Javascript和C#中的使用方法
- 在javaScript中关于submit和button的区别介绍
- 在ASP.NET中使用JavaScript脚本的方法
- javascript函数中执行c#函数的方法
- javascript中兼容主流浏览器的动态生成iframe方法
- JavaScript中实现最高效的数组乱序方法
- JavaScript实现继承的4种方法总结
- JavaScript-RegExp对象只能使用一次问题解决方法
- JavaScript中对象property的读取和写入方法介绍
- javascript在IE下trim函数无法使用的解决方法