1.创建新 JavaScript 对象有很多不同的方法
源码
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <script> //常用的 var person1={ name : "丁少华", sex : "男", age : 20 }; alert(person1.name) //其它的 person2=new Object(); person2.name="王新"; alert(person2.name) //模仿java function person3(name,age){ this.name=name; this.age=age; } dsh=new person3("康熙",20); alert(dsh.name) </script> </body> </html>
尝试比较java创建对象 (*^__^*)
public class person3 { String name; int age; person3(String name,int age){ this.name=name; this.age=age; } public static void main(String[] args) { person3 dsh=new person3("康熙",20); System.out.println(dsh.name); } }
突发奇想,既然js也是面向对象。那么就按照java的方式来创建对象。结果确保错
于是,百度一下,哦,好吧,是有区别,但区别又不大。
1.构造方法不用包含在person3类里
2.创建对象也不用写在函数里
3.构造函数也不需要数据类型
2.-js创建对象,对象调用方法
前言:js的方法是可以直接执行的,不用任何对象或类(它也没类),但是我们这里讲的是嵌套方法
源码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <script> //构造函数里写 :初始化以及方法 //因为js里没有类的概念,就把类方法也写在构造函数里 function People(age){ this.age=age; this.tt=function(){alert(age+1)}; } dsh=new People(20);//实例化对象 dsh.tt() </script> </body> </html>
试比较java
public class sudent { //声明变量 int age; //构造函数 sudent(int age){this.age=age;} //方法 void test(){ System.out.println(age+5); } //主方法:程序从这里执行 public static void main(String[] args) { sudent dsh=new sudent(5);//创建对象 dsh.test();//执行test方法 } }
初始化即执行
源码
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <script> //构造函数里写 :初始化以及方法 //因为js里没有类的概念,就把类方法也写在构造函数里 function People(age){ this.age=age; (function(){alert(age+1);})()//js立即执行函数 } dsh=new People(20);//实例化对象 </script> </body> </html>
试比较java
public class sudent { //声明变量 int age; sudent(int age){this.age=age; test();} //方法 void test(){ System.out.println(age+5); } //主方法:程序从这里执行 public static void main(String[] args) { sudent dsh=new sudent(5);//创建对象 } }
结论。
调用方法方面,因为js没有类的概念,所以什么都需要在类似构造的那个函数里写上,严格来说那个函数并不是构造函数。
如果想要初始即执行的话,java是直接写在构造里的,而js则会报错,js有专用的立即执行函数格式
3、(后续)
新版的ES6可以直接用后台语法去写js啦,也有了类的概念。不要惊讶,应为语言本相同嘛,在说了,js语法本就松散,模仿能力又强
<script type="text/javascript"> class Student{ constructor(name) {this.name = name;}//构造函数 sayName() {console.log("My name is "+this.name);}//方法 } var dsh=new Student("丁少华"); dsh.sayName(); </script>
继承,-----像是完全抄袭java的了
<script type="text/javascript"> class People{ constructor(name) {this.name = name;}//构造函数 sayName() {console.log("My name is "+this.name);}//方法 } class Student extends People{ constructor(name) {super(name);}//直接调用父类构造器进行初始化 speak(){console.log("我叫"+this.name);} } var dsh=new Student("丁少华"); dsh.speak(); </script>