下のコードでは、オブジェクトを連鎖させてタスクを委任しようとしています。私の目標は、チェーンの「トップ」でメディアオブジェクトを持つことであるので、同様に下部にある曲の各インスタンスを持つ:メディア< - 歌< - songXYZobject.createとchainingオブジェクト
はJavaScript:
var playlistElement = document.getElementById("playlist");
var playButton = document.getElementById("play");
playButton.onclick = function() {
playlist.play();
playlist.renderInElement(playlistElement);
};
var nextButton = document.getElementById("next");
nextButton.onclick = function() {
playlist.next();
playlist.renderInElement(playlistElement);
};
var stopButton = document.getElementById("stop");
stopButton.onclick = function() {
playlist.stop();
playlist.renderInElement(playlistElement);
};
var playlist = {
init: function() {
this.songs = [];
this.nowPlayingIndex = 0;
},
add: function(song) {
this.songs.push(song);
},
play: function() {
var currentSong = this.songs[this.nowPlayingIndex];
currentSong.play();
},
stop: function() {
var currentSong = this.songs[this.nowPlayingIndex];
currentSong.stop();
},
next: function() {
this.stop();
this.nowPlayingIndex++;
if (this.nowPlayingIndex === this.songs.length) {
this.nowPlayingIndex = 0;
}
this.play();
},
renderInElement: function(list) {
list.innerHTML = "";
for (var i = 0; i <this.songs.length; i++) {
list.innerHTML += this.songs[i].toHTML();
}
}
};
var media = {
init: function(title, duration) {
this.title = title;
this.duration = duration;
this.isPlaying = false;
},
play: function() {
this.isPlaying = true;
},
stop: function() {
this.isPlaying = false;
}
};
var song = Object.create(media);
song = {
setup: function(title, artist, duration) {
this.init(title, duration);
this.artist = artist;
},
toHTML: function() {
var htmlString = '<li';
if(this.isPlaying) {
htmlString += ' class="current"';
}
htmlString += '>';
htmlString += this.title;
htmlString += ' - ';
htmlString += this.artist;
htmlString += '<span class="duration">'
htmlString += this.duration;
htmlString += '</span></li>';
return htmlString;
}
};
playlist.init();
var song1 = Object.create(song);
song1.setup("Here comes the Sun", "The Beatles", "2:54");
var song2 = Object.create(song);
song2.setup("Walking on Sunshine", "Katrina and the Waves", "3:43");
playlist.add(song1);
playlist.add(song2);
playlist.renderInElement(playlistElement);
Object.create()を使用してオブジェクトを互いに委譲させています。クロームのdevのツールによると
var song1 = Object.create(song);
song.isPrototypeOf(:経由
var song = Object.create(media);
と私は曲のオブジェクトにデリゲートを作成し、各曲:経由
メディアオブジェクトへの曲のオブジェクトの代表者は、 song1)=== true、しかしmedia.isPrototypeOf(song)=== falseです。私はsong1とsongをリンクさせたのと同じコードをメディアにリンクしています。また、this.initは関数ではないと言われています。しかし、ソング1やソングオブジェクトに見つからないときはチェーンを委任し、メディアオブジェクトで見つける必要があります。私がコメントで言ったようにhttps://jsfiddle.net/n3q64nq4/
。 song = {...} 'は2つのオブジェクトを作成します。最初は即座に忘れられ、もう1つは' media'とは無関係です。 – Amadan