JS 面向对象,以及静态方法与实例方法的调用区别

来源:互联网 发布:c语言编写 玫瑰花 编辑:程序博客网 时间:2024/06/01 12:36

//面向对象:构造函数+原型 方式,创建 类;使用:(function(){  ...  })();  包起来 是因为在js中没有块级作用域(新的ES标准已经有了,这里就不说了),这种写法是为了防止

//里面的变量污染外面的变量!

(function() {


var Person = function(name, age) {
this.name = name;
this.age = age;
};


Person.prototype = {
eat: function() {
console.log("每个人都要吃饭!" + this.name + ",也不例外");
},
sleep: function() {
console.log("每个人都要睡觉!" + this.age + " 岁的年龄每年都会长大!");
}
};

Person.initFunc=function(){
console.log("我是Person类里的静态方法,只能通过类来访问!");
};

//这里把当前类 Person 赋值给顶级变量 window 以便 外部调用!
window["Person"] = Person;


})();


//静态方法 与 实例方法

var Student = function() {};

Student.read = function() {
console.log("每一个学生都要努力学历,多读书!");
};

Student.prototype = {
sayHello: function() {
console.log("我要上学校!早早早!");
},
};

var xiaoMing = new Student();


//静态方法,无需实例化调用,直接 类名. 调用!
Student.read();

//sayHello 是原型链上的方法,只有通过实例化这个类,他才会在内存上开辟空间,才能通过实例对象调用!
//Student.sayHello(); //Error: sayHello() is not a function;

//同样 这里报错   read 是一个静态方法,不是通过 实例名. 来调用!
//xiaoMing.read();  //Error: read() is not a function; 
xiaoMing.sayHello();

阅读全文
0 0
原创粉丝点击