JavaScript中的构造函数

来源:互联网 发布:快图浏览 知乎 编辑:程序博客网 时间:2024/04/28 05:24

JavaScript和Java一样,都是面向对象语言的。但是不同的是,JavaScript没有class的概念。因此,JavaScript的构造函数和Java等面向对象语言的构造函数会有所不同。

在Java中,一个普通的构造函数可以是这样的:

public class Person {private String name;private int age;private String[] hobbies;public Person(String name,int age,String[] hobbies) {this.name = name;this.age = age;this.hobbies = hobbies;}public void print() {System.out.println("我的名字叫" + name + ",我的年龄是" + age + "我的爱好是" + Arrays.toString(hobbies));}}

我们可以这样用它:

public static void main(String[] args) {Person p = new Person("Mike",22,new String[]{"篮球","羽毛球","高尔夫"});p.print();}

输出结果:

我的名字叫Mike,我的年龄是22我的爱好是[篮球, 羽毛球, 高尔夫]

再看看JavaScript的构造函数长什么样子:

// 构造函数function Person(name,age,hobbies) {this.name = name;this.age = age;this.hobbies = hobbies;this.print = function() {console.info('我的名字叫' + this.name + ',我的年龄是' + this.age + '我的爱好是' + this.hobbies);}}

这里应该注意的是构造函数其实就是一个普通的函数,只不过函数体内部使用了this(当前对象).

使用它看看:

var mike = new Person('Mike',22,["篮球","羽毛球","高尔夫"]);mike.print();

控制台打印消息(F12):

我的名字叫Mike,我的年龄是22我的爱好是篮球,羽毛球,高尔夫 


原创粉丝点击