jQuery creating objects [duplicate]

2020-06-07 07:34发布

How would I create an object in jQuery, and then proceed to make a couple of different instances of this object I.e

Create an object named box which holds a variable called color.

And then make a couple of instances of this object with different stored colours.

标签: jquery oop
4条回答
淡お忘
2楼-- · 2020-06-07 07:39

May be you want this (oop in javascript)

function box(color)
{
    this.color=color;
}

var box1=new box('red');    
var box2=new box('white');    

DEMO.

For more information.

查看更多
一纸荒年 Trace。
3楼-- · 2020-06-07 07:41

You can always make it a function

function writeObject(color){
    $('body').append('<div style="color:'+color+';">Hello!</div>')
}

writeObject('blue')enter image description here

查看更多
Root(大扎)
4楼-- · 2020-06-07 07:53

I actually found a better way using the jQuery approach

var box = {

config:{
 color: 'red'
},

init:function(config){
 $.extend(this.config,config);
}

};

var myBox = box.init({
 color: blue
});
查看更多
成全新的幸福
5楼-- · 2020-06-07 08:01

Another way to make objects in Javascript using JQuery, getting data from the dom and pass it to the object Box and, for example, store them in an array of Boxes, could be:

var box = {}; // my object
var boxes =  []; // my array

$('div.test').each(function (index, value) {
    color = $('p', this).attr('color');
    box = {
        _color: color // being _color a property of `box`
    }
    boxes.push(box);
});

Hope it helps!

查看更多
登录 后发表回答