本文实例讲述了javascript 高级语法之继承的基本使用方法。分享给大家供大家参考,具体如下:
高级语法的基本使用
<script type="text/javascript"> //声明一个函数demo function Demo() { } //实例函数demo var demo = new Demo(); //声明一个函数Demo1 function Demo1(name,age) { this.name = name; this.age = age; } //实例一个函数Demo1 var demo1 = new Demo1('谭勇',21); //运行下面试试 console.log(demo1.name); console.log(demo1.age); //Demo2 function Demo2(name,age) { var that = this; this.name = name; this.age = age; function a() { return that.name; } function b() { return that.age; } this.getName = a; this.getAge = b; } //实例一个函数Demo1 var demo2 = new Demo2('谭勇',21); //运行下面试试 console.log(demo2.name); console.log(demo2.age); </script>
运行结果:
继承
<script type="text/javascript"> function Demo(name,age) { this.name = name; this.age = age; } function Son() { this.text = 'test text'; } Son.prototype = new Demo('谭勇',22); var __son = new Son(); //试试 console.log(__son.name); console.log(__son.age); console.log(__son.text); //组合继承 function Son1() { this.text1 = 'my test son1'; } Son1.prototype.Demo = new Demo('谭勇',22); Son1.prototype.Son1 = new Son1(); var __son1 = new Son1(); console.log(__son1.Demo.name); console.log(__son1.Demo.age); console.log(__son1.Son1.text); console.log(__son1.text1); </script>
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!