1. JS 对象
<script>
var Person = new Object();
Person.id = 1;
Person.name = "Hello World";
Person.age = 10;
Person.Func_eat = function(food)
{
console.log("eat:" + food);
}
Person.Func_eat("vegetable");
Person2 = new Person(); //没有声明 Person 方法,报错
Person2.Func_eat("fruit");
</script>
上例是:直接创建一个对象的实例,但是没有为“这一类对象”定义构造函数。
使用构造创建对象,并有对象来初始化实例:
<script> function Person(id, name, age) { this.id = id; //this 指向该函数所属的对象 this.name = name; this.age = age; this.eat = function(food) { console.log(this.name + " eat:" + food); } } XiaoMing = new Person(1, "XiaoMing", 10); XiaoMing.eat("meet"); LiLei = new Person(2, "LiLei", 12); LiLei.eat("fruit"); </script>
2016.10.2 补充:
用Chrome 可以调试 HTML 里的 JS 脚本:
Egret 使用的类的定义方式:
var egret; (function (egret) { /** * @private */ function _getString(code) { var params = []; for (var _i = 1; _i < arguments.length; _i++) { //arguments:JS关键字,函数参数数组; params[_i - 1] = arguments[_i]; } return egret.sys.tr.apply(egret.sys, arguments); } })(egret || (egret = {}));
- 常见格式:(function() { /* code */ })();
- 解释:包围函数(function(){})的第一对括号向脚本返回未命名的函数,随后一对空括号立即执行返回的未命名函数,括号内为匿名函数的参数。
- 作用:可以用它创建命名空间,只要把自己所有的代码都写在这个特殊的函数包装内,那么外部就不能访问,除非你允许(变量前加上window,这样该函数或变量就成为全局)。各JavaScript库的代码也基本是这种组织形式。
2. 常用JS处理的 HTML 事件:
onchange | HTML 元素改变 |
onclick | 用户点击 HTML 元素 |
onmouseover | 用户在一个HTML元素上移动鼠标 |
onmouseout | 用户从一个HTML元素上移开鼠标 |
onkeydown | 用户按下键盘按键 |
onload | 浏览器已完成页面的加载 |
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <button onclick="console.log(PrintDate())">现在的时间是?</button> <button onclick="this.innerHTML=PrintDate()">现在的时间是?</button> <script> function PrintDate() { return Date(); } </script> </body> </html>
标签都是用字符串描述的,onclick=PrintDate() 是新手容易犯的错误。
3. JS的运算符
常用运算符与C/C++相同,不赘述。
4. 类型转换
typeof() 可用于类型检查,在弱类型的脚本语言里还是很常用的。
<script> function PrintDate() { return Date(); } console.log(typeof(PrintDate)) </script>
输出 “function”。
用 constructor 可以起到类似的效果:
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
类型转换:
<script> var num = 123; console.log(num.toString()); // Number方法-直接转换为字符串 console.log(num.toExponential()); // Number方法-转换为指数计数法 console.log(num.toFixed(3)); // Number方法-转换为字符串,小数点后带指定位数 console.log(num.toPrecision(5)); // Number方法-转换为指定长度字符串 console.log(Date().toString()); </script>
4. 时间API
getDate() | 从 Date 对象返回一个月中的某一天 (1 ~ 31)。 |
getDay() | 从 Date 对象返回一周中的某一天 (0 ~ 6)。 |
getFullYear() | 从 Date 对象以四位数字返回年份。 |
getHours() | 返回 Date 对象的小时 (0 ~ 23)。 |
getMilliseconds() | 返回 Date 对象的毫秒(0 ~ 999)。 |
getMinutes() | 返回 Date 对象的分钟 (0 ~ 59)。 |
getMonth() | 从 Date 对象返回月份 (0 ~ 11)。 |
getSeconds() | 返回 Date 对象的秒数 (0 ~ 59)。 |
getTime() | 返回 1970 年 1 月 1 日至今的毫秒数。 |