簡體   English   中英

我如何在jQuery之類的函數內部執行變量對象?

[英]How can I do variable object inside of function like jQuery do?

我有此功能來顯示通知

var notification_box = {
    notification: function (msg) {
        $('#notification_box').animate({
            top: "100"
        }).text(msg)
    }
}

我用

notification_box.notification("wwaaaa");

如何用這個聲明函數?

notification_box.notification({
    msg: "wwaaaa"
});

通過使用點符號或括號符號。

您傳遞對象的功能, notificationobject notification_box 在函數msg指向您已傳遞的對象。 該函數的一個屬性是msg ,因此msg.msg (或msg['msg'] )是訪問變量的方式。

 var notification_box = { notification: function(msg) { $('#notification_box').animate({ top: "100" }).text(msg.msg) //look at the dot notation here, it refers to the object } } notification_box.notification({ msg: "wwaaaa" }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="notification_box"></div> 


使用gettersetter甚至更酷的是defineProperty

 var notification_box = {"notify_message" : ""}; Object.defineProperty(notification_box, "notification", { get : function(){return this.notify_message;}, set : function(value){ $('#notification_box').animate({top: "100"}).text(value); this.notify_message = value; } }); //set notification_box.notification = "waaaaaaa"; //get console.log(notification_box.notification); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="notification_box"></div> 

可以使用點表示法將json傳遞給函數

object.attribute

在您的情況下使用

msg.msg  #First msg is javascript object and second msg is attribute

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM