1.
= =是判别左右相等为真
!= 是判别左右不相等为真
2.function同名字,会执行后面的
function changeStyle() { var p = document.getElementById("pAugust"); p.style.fontSize = "3rem"; p.style.color = "red"; }
3.function使用方式:
function 1.先宣告 2.再使用
(1)直接写
function func4(n) { // return "flower"; return n * n; } var temp = func4(5); //使用 console.log(temp);
(2)宣告 var = function ()
var demo = function () { console.log("ok"); }; demo(); //使用
(3)var func5 = function (something)
var func5 = function (something) { console.log(something); } func5("yoyo"); //使用
(4)建立物件 大写、this
function Student(sname, sage) { //S O this.StudentName = sname; //this S this.StudentAge = sage; //this S this.cat = function () { console.log("喵"); console.log(this.StudentName); //物件里面的属性 this }; } var s2 = new Student("No2", 90); //new O console.log(s2.StudentName); // cat s2.cat(); //"喵" console.log("\n\n");
4.不要做错误的事情:5000开[]塞东西?? a[0]不会开 一样5000
function mysetInterval(a, b) { a[0] = "apple"; // 5000 console.log(a); console.log(b); } mysetInterval(5000, 1000); //5000 ,1000
5.function精简:箭头函式
正常
var b = function () { return "bunny"; }; var temp = b(); console.log(temp); // bunny
精简:function拿掉 => 箭头函式
var b = () => { return "bunny-2"; }; var temp = b(); console.log(temp); // bunny-2
更精简 如果「只做return」,{} 和 return 都可以省略
var b = () => "bunny-3"; //{} return 拿掉 var temp = b(); console.log(temp); // bunny-3
但如果需要多个陈述句子,还是需要加上 () => {}
var c = () => { var x = 5 + 8; //多的陈述 return x; }; var temp = c(); console.log(temp); // 13
6.this的使用
console.log(this); // window 物件 console.log(window === this); //true
(1)如果单纯使用this(非製作物件),会到另一个世界去(window)
此时程式只能用特定方式使用,不适用正常code
var s1 = { html: 100, css: 90, getTotal: function () { //不能改成=>函式,this 已经是另一个世界(window)不适用正常code return this.html + this.css; //this 没有this会变成抓变数 }, }; var temp = s1.getTotal(); console.log(temp); // 190
(2)製作物件(同前function)
function Student(sname, sage) { //S O this.StudentName = sname; //this S this.StudentAge = sage; //this S this.cat = function () { console.log("喵"); console.log(this.StudentName); //物件里面的属性 this }; } var s2 = new Student("No2", 90); //new O console.log(s2.StudentName); // cat s2.cat(); //"喵" console.log("\n\n");