RC1*_*140 19 javascript inheritance extjs prototypal-inheritance
虽然我知道你不能像在C#中那样执行继承,但我已经看到它在互联网上提到它有可能.如果使用普通的JavaScript代码是不可能的话那么可以使用Ext JS吗?如果可以的话怎么样?
CMS*_*CMS 48
面向JavaScript面向对象的范例是基于原型的.没有"类",只有对象.
您可以以不同的方式实现继承.两种更受欢迎的替代品是"伪经典"和"原型"形式.例如:
我认为这是最受欢迎的方式.您可以创建与new运算符一起使用的构造函数,并通过构造函数原型添加成员.
// Define the Person constructor function
function Person() {}
Person.prototype.sayHello = function(){
alert ('hello');
};
// Define the Student constructor function
function Student() {}
// Inherit from Person
Student.prototype = new Person();
// Correct the constructor pointer, because it points to Person
Student.prototype.constructor = Student;
// Replace the sayHello method (a polymorphism example)
Student.prototype.sayHello = function () {
alert('hi, I am a student');
}
var student1 = new Student();
student1.sayHello();
Run Code Online (Sandbox Code Playgroud)
基本上我们创建一个辅助函数,它将一个对象作为参数,并返回一个从旧对象继承的空对象,对象继承自对象.
// Helper function
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
var person = {
sayHello : function () {
alert('Person object');
},
walk : function () {
alert('walk');
}
};
var student1 = Object.create(person);
student1.sayHello = function () {
alert('hello I am a student');
};
Run Code Online (Sandbox Code Playgroud)
另一个有趣的形式是寄生遗传.在"派生"构造函数中,您将创建一个"基础"对象实例.该对象被扩充并返回新实例:
// Person constructor function
function Person(name) {
this.name = name;
}
function Student(value) {
var that = new Person(value);
that.sayHello = function () {
alert('hello I am a student');
};
return that;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12728 次 |
| 最近记录: |