<script type="text/javascript">
//原型
var Test = function() {};
//Test对象本身的方法
Test.sayHello = function() {
alert('Hello, Test!');
};
//Test实例化对象的方法
//函数对象会有一个prototype属性,指向这个函数的原型对象,原型对象相当于一个类
Test.prototype.sayHello = function(){
alert('Hello, Test prorotype!');
};
var obj = new Test();
obj.sayHello(); //调用Test.prototype.sayHello
Test.sayHello(); //调用Test.sayHello
//原型链
function Student() {}
Student.prototype.sayHello = function() {
alert("Hello, I'm a student!");
}
function CollegeStudent() {}
//设置CollegeStudent的prototype属性为Student的实例对象
CollegeStudent.prototype = new Student();
CollegeStudent.prototype.property = 'college student';
//修改CollegeStudent.prototype.constructor为CollegeStudent本身
CollegeStudent.prototype.constructor = CollegeStudent;
//创建CollegeStudent的一个实例
var s = new CollegeStudent();
//s对象从CollegeStudent.prototype和Student.prototype继承属性和方法
alert(s.property);
s.sayHello();
//当查找一个对象的属性时,会遍历原型链,一直往顶层Object找,如果没有找到,则返回undefined。
/*
s [CollegeStudent的实例]
CollegeStudent.prototype [Student的实例]
Student.prototype
Object.prototype
*/
</script>
//原型
var Test = function() {};
//Test对象本身的方法
Test.sayHello = function() {
alert('Hello, Test!');
};
//Test实例化对象的方法
//函数对象会有一个prototype属性,指向这个函数的原型对象,原型对象相当于一个类
Test.prototype.sayHello = function(){
alert('Hello, Test prorotype!');
};
var obj = new Test();
obj.sayHello(); //调用Test.prototype.sayHello
Test.sayHello(); //调用Test.sayHello
//原型链
function Student() {}
Student.prototype.sayHello = function() {
alert("Hello, I'm a student!");
}
function CollegeStudent() {}
//设置CollegeStudent的prototype属性为Student的实例对象
CollegeStudent.prototype = new Student();
CollegeStudent.prototype.property = 'college student';
//修改CollegeStudent.prototype.constructor为CollegeStudent本身
CollegeStudent.prototype.constructor = CollegeStudent;
//创建CollegeStudent的一个实例
var s = new CollegeStudent();
//s对象从CollegeStudent.prototype和Student.prototype继承属性和方法
alert(s.property);
s.sayHello();
//当查找一个对象的属性时,会遍历原型链,一直往顶层Object找,如果没有找到,则返回undefined。
/*
s [CollegeStudent的实例]
CollegeStudent.prototype [Student的实例]
Student.prototype
Object.prototype
*/
</script>