实例1、js的基础语法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js基础语法</title> <script type="text/javascript" > //字面量输出 // document.write('hahahahaha'); // console.log('犇犇'); function add(){ let m= arguments.length; //返回参数的数量 switch(m){ case 0: return '至少一个参数'; break; case 1: return arguments[0]; break; case 2: return arguments[0]+arguments[1]; break; case 3: return arguments[0]+arguments[1]+arguments[2]; break; default: return '参数过多'; break; } } console.log(add(10,20,30,40)); </script> </head> <body> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例
实例 js创建对象1
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>对象</title> <script > let obj = new Object();//创建函数 obj.name='chang'; obj.age=1; obj.getName=function(){return this.name}; obj.getAge=function(){return this.age}; console.log(obj.getName()); console.log(obj.getAge()); let obj1 = { name:'benben', 'sex':'baby', getName:function (){return this.name}, getSex:function (){return this.sex} } // obj1.name; console.log(obj1.name); console.log(obj1.getName()); console.log(obj1['sex']); console.log(obj1.getSex()); console.log(obj1); </script> </head> <body> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例
实例 js创建对象2
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>创建对象</title> <script type="text/javascript"> //1、创建函数 (方法) 用来创建对象 function creatObj(name,age){ let obj = new Object(); obj.name= name; obj.age=age; return obj; } let obj1=creatObj('ben',1); let obj2=creatObj('ben2',1); let obj3=creatObj('ben3',1); console.log(obj1); console.log(obj2); console.log(obj3); //2、创建构造函数 (方法) 由工厂函数演变而来 function Stu(name,age){ // let obj = new Object(); this.name = name; this.age = age; this.getName = function(){ return this.name; } // return obj; } //new Stu('benben',2); //相当于 let obj4 = new Stu('benben',2); console.log(obj4); // 3、原型:所有实例可共享的属性或方法 function Stu(){ } //实现方法的共享 Stu.prototype.getName=function(){ return this.name; } Stu.prototype.name='benbenben'; Stu.prototype.age=3; let obj5 = new Stu(); console.log(obj5); </script> </head> <body> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例