単に使用するsettings.closeButton.text
JavaScript プロパティには、次の 2 つの方法のいずれかを使用してアクセスできます。
ドット表記
プロパティにアクセスする最も一般的で基本的な方法 - ただし、不正な変数名 (予約語を除く - ES5 ではプロパティ名として許可されています) は機能しません。
foo.bar; // OK
foo.class; // only in ES5 and up
foo.&^&%^&@&(@&&@; // SyntaxError: yeah, it doesn't work
角括弧表記
角かっこ表記を使用する場合、何でもかまいませんが、文字列に変換されます (JavaScript のすべてのオブジェクト プロパティは文字列です)。
// both are the same
foo['bar'];
foo["bar"];
// this is fine
foo['&^&%^&@&(@&&@'];
// this is equivalent to foo["[object Object]"]
foo[{}];
お好きな方法を選んでください - ただし、必要がない限り、ドット表記を使用して JavaScript オブジェクトのプロパティにアクセスする方がおそらく簡単です。
編集: jsFiddle について、これが機能しない理由は次のとおりです。
var options = {
// Passing these options in
msg: 'This is my message',
closeButton: {
text: "Close this",
colour: "red"
}
},
// These are the defaults if none are passed in
settings = $.extend({
title: 'Default Title',
msg: 'Default message',
closeButton: {
text: "Close",
colour: "red",
btnClass: "pull-right"
}
}, options);
console.log(settings.closeButton.text);
console.log(settings.closeButton.colour);
console.log(settings.closeButton.btnClass);
/*
settings.closeButton.text
settings.closeButton.colour
settings.closeButton.btnClass
*/
を呼び出しているとき$.extend()
、後の引数のプロパティは前の引数のプロパティを置き換えます。この場合、引数は後で指定されているため、呼び出しのプロパティは のcloseButton
プロパティに$.extend()
置き換えられます。options
これが実際の動作の例です:
var a = { foo: 'bar' };
var b = { foo: 'baz' };
var c = $.extend(a, b);
var d = $.extend(b, a);
console.log(c.foo); // baz (b was last argument)
console.log(d.foo); // bar (a was given last)
この問題を解決するには、引数を交換するか、引数の先頭に を追加してディープ コピーを実行します (この場合は許容範囲です) true
。
$.extend({ a: { b: 1, c: 2 } }, { a: { b: 3 } }).a; // { b: 3 }
$.extend(true, { a: { b: 1, c: 2 } }, { a: { b: 3 } }).a; // { b: 3, c: 2 }