理解javascript中的OOP
对于理解javascript面向对象开发,我是个新手。因此,我正在阅读jQuery源代码,并试图通过在自定义libs中实现相同的概念来理解它,尽管目标不是复制代码,而是以面向对象的方式创建一些函数理解javascript中的OOP,javascript,jquery,Javascript,Jquery,对于理解javascript面向对象开发,我是个新手。因此,我正在阅读jQuery源代码,并试图通过在自定义libs中实现相同的概念来理解它,尽管目标不是复制代码,而是以面向对象的方式创建一些函数 (function (window) { var myCustomClass = function () { debugger; return new myCustomClass.mycustomFunction.Init(); }; myCustomClass.mycustomFun
(function (window) {
var myCustomClass = function () {
debugger;
return new myCustomClass.mycustomFunction.Init();
};
myCustomClass.mycustomFunction= myCustomClass.prototype = {
Init: function () {
return this;
},
alert: function () {
alert('I got called');
}
};
window.$ = window.mQuery = myCustomClass;
})(window);
并尝试以这种方式使用:
mQuery().alert();
但这是一个错误,我试图找出它,但没有用。我想,我遗漏了一些概念,请告诉我正确的方向。查看jQuery源代码并尝试模仿它的概念并不一定是启动javascript OOP学习曲线的好方法。我建议您先从一些简单的和基础的书籍开始,在尝试从源代码理解一个相当复杂的库之前,先逐步学习 如果您正在寻找从构造函数“jQuery样式”链接函数的方法,您可以尝试以下简单模式作为启动程序:
var myCustomClass = function() {
// initialize a new instance
if(!(this instanceof myCustomClass)) {
return new myCustomClass();
}
};
myCustomClass.prototype = {
constructor: myCustomClass,
// add some custom methods
alert: function() {
window.alert.apply(window, arguments);
return this;
},
write: function(str) {
document.body.innerHTML = str;
return this;
}
};
myCustomClass().alert('foo').write('bar');
查看jQuery源代码并尝试模仿其概念并不一定是启动javascript OOP学习曲线的好方法。我建议您先从一些简单的和基础的书籍开始,在尝试从源代码理解一个相当复杂的库之前,先逐步学习 如果您正在寻找从构造函数“jQuery样式”链接函数的方法,您可以尝试以下简单模式作为启动程序:
var myCustomClass = function() {
// initialize a new instance
if(!(this instanceof myCustomClass)) {
return new myCustomClass();
}
};
myCustomClass.prototype = {
constructor: myCustomClass,
// add some custom methods
alert: function() {
window.alert.apply(window, arguments);
return this;
},
write: function(str) {
document.body.innerHTML = str;
return this;
}
};
myCustomClass().alert('foo').write('bar');
这是理解JavaScript OOP的良好开端。特别是第6章和第8章。感谢您的即时回复,我已经掌握了JS OOPS的基本知识,但在应用它的过程中仍然面临一些问题。请查看了解jQuery糟糕的OOP模式-不要经常使用它。。这有助于理解JavaScript OOP。特别是第6章和第8章。感谢您的即时回复,我已经掌握了JS OOPS的基本知识,但在应用它的过程中仍然面临一些问题。请查看了解jQuery糟糕的OOP模式-不要经常使用它。。我已经更改了代码,这只是一个输入错误,我不打算编写它,直到您忘记了一些重要的部分,例如从类原型复制Init原型:
myCustomClass.mycustomFunction.Init.prototype=myCustomClass.prototype
。但是,如果你不知道它是做什么的,或者它是如何工作的,你为什么要实施它呢?@paritosh如果它解决了你的问题,你可以接受答案。。。非常感谢。实际上我想了解这些概念,目前我正在阅读Dan发布的eloquentjavascript.net/contents.html,如果您有任何想法,请与我们分享。我已经更改了代码,这只是一个打字错误,我不打算编写它,直到,你忘记了一些重要的部分,比如从类原型复制Init原型:myCustomClass.mycustomFunction.Init.prototype=myCustomClass.prototype
。但是,如果你不知道它是做什么的,或者它是如何工作的,你为什么要实施它呢?@paritosh如果它解决了你的问题,你可以接受答案。。。非常感谢。实际上我想了解这些概念,目前我正在阅读Dan发布的eloquentjavascript.net/contents.html,如果您有任何想法,请与我们分享。这样我就能对同样的问题有更多的了解。