![](/img/trans.png)
[英]Clock Angle Problem --> How Do I call an Object Outside of a Function and Assign the Object Value to a Variable Inside Function
[英]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"
});
通過使用點符號或括號符號。
您傳遞對象的功能, notification
在object
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>
使用getter
和setter
甚至更酷的是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.