运行 节点上函数内部的方法
Running method inside of a function on a node
我无法理解下面代码片段的工作原理。
const video = player.querySelector('.viewer');
function togglePlay() {
const method = video.paused ? 'play' : 'pause';
video[method];
}
togglePlay() //starts playing video
我不明白的确切部分是视频[方法],它是如何工作的?我试过 google 它,但到目前为止运气不好。我们只是向视频对象添加一个方法吗?如果是这样,为什么我们调用 togglePlay() 它开始播放视频?!
其工作方式是访问视频对象的属性。这意味着我们像数组一样使用视频。如果视频暂停,我们会找到播放方法,否则我们会找到暂停方法。我们不是在创建新方法,我们只是在寻找对象上已经存在的方法。
如果您愿意,可以将代码重写为
function togglePlay() {
if(video.paused) {
video.play() // could also be written as video["play"]()
} else {
video.pause() // could also be written as video["pause"]()
}
}
要使 togglePlay 方法像您编写的那样工作,您必须将 togglePlay 函数的最后一行更改为此。
视频[方法]到视频[方法]();
const video = document.getElementById("video");
function togglePlay() {
const method = video.paused ? 'play' : 'pause';
video[method]();
}
<!DOCTYPE html>
<html>
<body>
<video id="video" width="320" height="240" controls>
<source src="https://www.w3schools.com/html/movie.mp4" type="video/mp4">
<source src="https://www.w3schools.com/html/movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
<button onclick="togglePlay()">toggle play</button>
</body>
</html>
我无法理解下面代码片段的工作原理。 const video = player.querySelector('.viewer');
function togglePlay() {
const method = video.paused ? 'play' : 'pause';
video[method];
}
togglePlay() //starts playing video
我不明白的确切部分是视频[方法],它是如何工作的?我试过 google 它,但到目前为止运气不好。我们只是向视频对象添加一个方法吗?如果是这样,为什么我们调用 togglePlay() 它开始播放视频?!
其工作方式是访问视频对象的属性。这意味着我们像数组一样使用视频。如果视频暂停,我们会找到播放方法,否则我们会找到暂停方法。我们不是在创建新方法,我们只是在寻找对象上已经存在的方法。
如果您愿意,可以将代码重写为
function togglePlay() {
if(video.paused) {
video.play() // could also be written as video["play"]()
} else {
video.pause() // could also be written as video["pause"]()
}
}
要使 togglePlay 方法像您编写的那样工作,您必须将 togglePlay 函数的最后一行更改为此。
视频[方法]到视频[方法]();
const video = document.getElementById("video");
function togglePlay() {
const method = video.paused ? 'play' : 'pause';
video[method]();
}
<!DOCTYPE html>
<html>
<body>
<video id="video" width="320" height="240" controls>
<source src="https://www.w3schools.com/html/movie.mp4" type="video/mp4">
<source src="https://www.w3schools.com/html/movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
<button onclick="togglePlay()">toggle play</button>
</body>
</html>