jQuery和面向对象的JavaScript - howto? [英] jQuery and object-oriented JavaScript - howto?

查看:67
本文介绍了jQuery和面向对象的JavaScript - howto?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过这个这个(谢谢谷歌)
但它没有没有足够的帮助。我想知道,如果,开箱即用,没有任何插件插件,可以做一些像原型一样的事情,例如:

I've read this and this (thanks google) But it doesn't help enough. I'd like to know, if, straight out of the box, without any plugin addons, it's possible to do something like it's possible with prototype, for example:

MyClass = Class.create(Table,
{
  cookieName: 'w_myclass',
  prefix: 'myclass',
    ...blabla...

  // function
  initStr: function()
  {
    ...blabla...
  },

  // another function
  getIndice: function(param)
  {
    ...blabla...
    return 0;
  }

});

欢迎任何想法/建议。

推荐答案

如果你想使用带有jquery的javascript的近似面向对象的解决方案,你可以在javascript中定义一个将设置你的事件控制器的对象。

If you want a near object oriented solution using javascript with jquery you can define an object in javascript that will set up your event controllers.

本文的后半部分 http://www.codescream.com/?p=18 涵盖那些。但我会在这里写一篇关于如何在javascript中创建一个可以在近物体导向结构中使用的对象的简历。

The second half of this post http://www.codescream.com/?p=18 covers that. but i'll write here a resume on how to make an object in javascript that you can use in a near object oriented structure.

它看起来像这样: / p>

It would look something like this:

function myObject(constructorParam1, constructorParam2, anotherOne, blabla){

  var text = "";
  // this event will be set everyTime you run myObject
  $(".foo").click(function(){
    text = $(this).text(); // copies the text inside the elements ".foo" to a local variable
    doSomething();
  });

  function aPrivateFunction1(){


  }

  function aPrivateFunction2(){

  }

  function internalAdd(a,b){
    return a+b;
  }

  var size = 1; // privateVaribale
  var name = blabla;


  if(name===undefined){
     name="No name";
  }

  aPrivateFunction1(); // run "aPrivateFunction1()

  // you can consider all code above as being part of the constructor.
  // The variables declared above are private, and the functions are private as well

  // bellow are public functions  that you can access in an OOP manner
  return {
    getSize: function(){
        return size;
    },

    setSize: function(newSize){
        size = newSize;
    },

    getName: function(){
        return name;
    },

    setName: function(newName){ 
        name = newname;
    },

    addAndTurnPositive: function(n1,n2){
        var val = internalAdd(n1,n2);
        if(val<0){
            return val*-1;
        }
        return val;
    }
  }
}

// then you can run it like
var anInstance = myObject("aaa",1234,"asdak",123);
anInstance.setSize(1234);
var t = anInstance.addAndTurnPositive(-5,2);

这篇关于jQuery和面向对象的JavaScript - howto?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆