我在过去使用的Prototype.js,并能编写类uing:jQuery的 - 如何编写类才达到OO设计
var XEventDesc = Class.create();
XEventDesc.prototype = {
initialize: function(element, eventName, handler, useCapture) {
....................
}
};
我怎样写使用jQuery
我在过去使用的Prototype.js,并能编写类uing:jQuery的 - 如何编写类才达到OO设计
var XEventDesc = Class.create();
XEventDesc.prototype = {
initialize: function(element, eventName, handler, useCapture) {
....................
}
};
我怎样写使用jQuery
似乎有一些jQuery插件可以做到这一点(例如,http://plugins.jquery.com/project/HJS)。但是,您可能会发现更适合您在jQuery之外的需求。
在JavaScript类你真的需要使用jQuery来创建一个类吗? JavaScript对象只是一个功能。
var Rectangle = function(width,height) {
//This section is similar to the initialize() method from prototypejs.
this.width = width;
this.height= height;
//Adding a method to an object
this.getArea = function() {
return this.width*this.height;
}
}
var myRect = new Rectangle(3,4);
alert(myRect.getArea()); //Alerts 12
我觉得这很有帮助。 – Adamantus 2012-02-23 16:29:08
要理解的基本原理是Javascript没有类的概念。它使用了所谓的原型继承。
JavaScript是基于“这是一个原型,大量生产它”,而不是“蓝图。从中建立对象”。 (函数代表类,因此您可以创建一个完全可用的函数,然后告诉Javascript使其更多,或者将其用作定义其他函数的参考点)
下面是关于这种范式以及如何实现继承的JS:(以防万一,他们中的一些在某种程度上解释了它,你有麻烦)
jQuery的支持一个延伸方法(http://api.jquery.com/jQuery.extend/),其通过允许你想要您与尽可能多的对象的属性扩展对象模仿多重继承。这只是模仿多重继承,因为它基本上使用for循环遍历其他对象的属性并将它们附加到目标对象 - 如果它实际上提供了多重继承,则可以添加/删除/修改属性从其中一个超级对象中获取并且具有由该子对象继承的更改,但事实并非如此。
要使用jQuery.extend,您需要提供目标对象作为第一个参数,以及其他参数将其扩展为以下参数。不过要小心,因为如果你只指定第一个对象,所有对象的属性将被用来扩展jQuery本身。
(function($) {
var SuperOne = {
methodOne: function() {
alert("I am an object");
},
methodTwo: function(param) {
// do something
}
},
SuperTwo = {
attributeOne: 'I am a super object',
getAttributeOne: function() {
return this.attributeOne;
},
setAttributeOne: function(attributeOne) {
this.attributeOne = attributeOne;
}
},
SubOne = $.extend({
subMethodOne: function() {
return 'I inherit from others.';
}
}, SuperOne, SuperTwo);
alert(SubOne.getAttributeOne()); ///<-- alerts, "I am a super object"
SuperTwo.setAttributeOne("I am SuperTwo!");
alert(SubOne.getAttributeOne()); ///<-- alerts, "I am a super object", still
SuperOne.methodOne = function() {
alert("I am SuperOne!");
};
SubOne.methodOne(); ///<-- alerts, "I am an object", instead of, "I am SuperOne!"
}(jQuery));
有人可以在标题中更改存档来实现吗? – kzh 2011-01-14 00:27:37