为内置对象添加原型方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
// 为内置对象添加原型方法
// var arr = [10,20,30,40];
// var arr = new Array(10,20,30,40);
// arr.join("|");
// console.dir(arr);
// var str = new String("哦,my gee");
// str.indexOf("gee");
// console.dir(str);
// 实例中的方法如果没有,去创建该实例对象的构造函数的原型对象中找
// var dt = new Date();
// dt.getFullYear();
// console.dir(dt);
// 我们能否为系统的对象的原型中添加方法,相当于在改变源码
// 我希望字符串中有一个倒序字符串的方法
String.prototype.myReverse = function(){
for(var i=this.length-1;i>=0;i--){
console.log(this[i]);
}
};
var str = "abcdefg";
str.myReverse();
// 为Array内置对象的原型对象中添加方法
Array.prototype.mySort = function(){
for(var i=0;i<this.length-1;i++){
for(var j=0;j<this.length-1-i;j++){
if(this[j]<this[j+1]){
var temp = this[j];
this[j] = this[j+1];
this[j+1] = temp;
}
}
}
};
var arr = [1,58,4,6,89,22];
arr.mySort();
console.log(arr);
String.prototype.sayHi = function(){
console.log(this+"哈哈,我又变帅了");
};
// 字符串就有了打招呼的方法
var str2 = "小杨";
str2.sayHi();
</script>
</head>
<body>
</body>
</html>
把局部变量编程全局变量
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
// 函数的自调用----自调用函数
// function f1(){
// console.log("函数");
// }
// f1();
// 一次性的函数----声明的同时,直接调用了
// (function(){
// console.log("函数");
// })();
// 页面加载后,这个自调用函数的代码就执行完了
// (function(形参){
// // 局部变量
// var num = 10;
// console.log("哈哈");
// })(实参);
// console.log(num);
(function(win){
// 局部变量
var num = 10;
// js是一门动态类型的语言,对象没有属性,点了就有了
win.num = num;
})(window);
console.log(num);
// 如何把局部变量变成全局变量
// 把局部变量给window就可以了
</script>
</head>
<body>
</body>
</html>