我正在处理我的 Rails 3.1 迁移,让 jquery 和原型(prototype)和平共处变得越来越难。我正在研究一种将我的原型(prototype)方式实现的 js 文件更改为 jquery 格式的方法。
我大量使用原型(prototype)方式来声明类和子类:
// properties are directly passed to `create` method
var Person = Class.create({
initialize: function(name) {
this.name = name;
},
say: function(message) {
return this.name + ': ' + message;
}
});
// when subclassing, specify the class you want to inherit from
var Pirate = Class.create(Person, {
// redefine the speak method
say: function($super, message) {
return $super(message) + ', yarr!';
}
});
var john = new Pirate('Long John');
john.say('ahoy matey');
// -> "Long John: ahoy matey, yarr!"
我读过 John Resig 的剧本:http://ejohn.org/blog/simple-javascript-inheritance/ .这是要走的路吗?还是应该选择其他方法?
我有大约 15 个 js 文件(每个文件一个类)。我愿意为这次迁移花费一些时间,所以我想把它做好。感谢您的专业帮助!
最佳答案
这是使用普通函数实现示例的一种可能方法。
function Person(name) {
this.name = name;
}
Person.prototype.say = function (message) {
return this.name + ": " + message;
};
function Pirate(name) {
this._super = Person.prototype;
this._super.constructor.apply(this, arguments);
}
Pirate.prototype.say = function (message) {
return this._super.say.apply(this, arguments) + ", yarr!";
};
john = new Pirate("Long John");
john.say("ahoy matey");
您可能希望将继承操作提取到一个函数中,但这为您提供了基本思路。
关于javascript - 如何将原型(prototype)类声明更改为 jquery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7710142/