JS——继承(创建共有属性和方法)
2017-11-21 11:08
302 查看
function Student(sname,sage) { //类型名首字母大写 this.sname = sname, this.sage = sage /*this.intr = function(){ //这个不能重用,占内存,需用继承 console.log("我是 "+this.sname+",我今年"+this.sage); }*/ } //共有方法 Student.prototype.intro = function(){ console.log("我是 "+this.sname+",我今年"+this.sage); } Student.prototype.className = "高一1班"; var stu1 = new Student("stu1",11); var stu2 = new Student("stu2",12); stu1.intro(); stu2.intro(); console.log(Student.prototype == stu1.__proto__); console.log(Student.prototype == stu2.__proto__); console.log(stu1.className); console.log(stu2.className); Student.prototype.className = "高二1班"; console.log(stu1.className); console.log(stu2.className);
代码整理后:
function Student(sname,sage){
this.sname = sname;
this.sage = sage;
}
Student.prototype.intr = function() {
console.log("I am" + this.sname + "age:" + this.sage);
}
Student.prototype.className = "高一1班";
var stu1 = new Student("stu1",11);
var stu2 = new Student("stu2",12);
stu1.intr();
stu2.intr();
console.log(stu1.className);
console.log(stu2.className);
Student.prototype.className = "高二2班";
console.log(stu1.className);
console.log(stu2.className);
console.log(Student.prototype == stu1.__proto__);
console.log(Student.prototype == stu2.__proto__);
相关文章推荐
- js创建数组的四种方法、常用方法、属性
- python进阶学习笔记(四)——python中访问限制、创建类属性、定义实例方法、定义类方法、类的继承
- js 创建类和继承的几种方法
- 创建js对象的属性和方法
- javascript的函数、创建对象、封装、属性和方法、继承
- javascript的函数、创建对象、封装、属性和方法、继承
- JS面向对象(3)之Object类,静态属性,闭包,私有属性, call和apply的使用,继承的三种实现方法
- JS的Object类的属性、方法及如何创建对象
- js 创建对象、属性、方法
- JS 实现 创建类、继承、方法添加、对象克隆、数组封装操作
- javascript的函数、创建对象、封装、属性和方法、继承
- JS面向对象(3) -- Object类,静态属性,闭包,私有属性, call和apply的使用,继承的三种实现方法
- js---17继承中方法属性的重写
- js 对象创建及其继承的方法
- javascript的函数、创建对象、封装、属性和方法、继承
- js动态创建/删除 (页面)元素节点、设置其属性方法
- js 创建对象、属性、方法
- JS创建对象方法以及继承方法
- JavaScript 中实现继承的方式(列举3种在前一章,我们曾经讲解过创建类的最好方式是用构造函数定义属性,用原型定义方法。)
- 通过js动态创建标签,并设置属性方法