nodebook/20191130/20191130.md
2019-12-03 00:14:50 +08:00

111 lines
2.3 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 20191130
![js](https://img.shields.io/badge/language-js-orange.svg)
给内置对象String添加原型方法相当于在改变String对象的源码
```js
var str = new String('abcdef')
String.prototype.myReverse = () => {
var str = ''
for( var i = this.length -1 ; i >= 0; i--) {
str += this[i]
}
return str
}
console.log(str.myReverse)
```
给内置对象Array添加原型方法
```js
Array.prototype.mySort = () => {
for(var i = 0; i < this.length; i++) {
for(var j = 0; j < this.length - i; j ++) {
if(this[j] > this[j+1]) {
var temp = this[j]
this[j] = this[j +1]
this[j+1] = temp
}
}
}
return this
}
var arr = new Array(1,2,3,4,5,6,7,8)
console.log(arr.mySort())
```
将局部变量变成全局变量
```js
// 匿名函数自执行
(function(){
console.log('哈哈哈')
})();
(function(){
console.log('哈哈哈')
}());
// 开始
(function(){
var num = 100
})();
console.log(num) // 报错不是undefined
// 传参方式
(function(win){
var num = 100
win.n = num
})(window);
console.log(n) // 打印100
```
undefined的情况
已定义未赋值
对象没定义的属性
函数并没有创建返回值
全局不一定是window 还可能使global
## 生成随机数
```js
// 生成随机数 -> 创建一个随机数对象 ---- 属性无 / 方法 -> 生成随机数
// 构造函数Random ---> 局部转全局 ---> 暴露给window ---> 实例化 ---> 调用方法 ---> 完成生成随机数
(function (window) {
// 创建随机数对象
function Random() {
}
Random.prototype.getRandom = (min, max) => {
// 0~5整数
return Math.floor(Math.random() * (max - min) + min)
}
window.Random = Random
}(window));
var random = new Random()
var num = random.getRandom(0, 5)
console.log(num)
```
js获取元素的方法
通过ID获取getElementById
通过name属性getElementsByName
通过标签名getElementsByTagName
通过类名getElementsByClassName
通过选择器获取一个元素querySelector
通过选择器获取一组元素querySelectorAll
获取html的方法document.documentElement
document.documentElement是专门获取html这个标签的
获取body的方法document.body
document.body是专门获取body这个标签的