1.类(使用构造函数实现一个类)
//构造函数:就是构造一个对象的函数(Java--构造函数和类名是相同的)
<script>
function Person(name,age){ //构造函数
this.name=name;
this.age=age
}
Person.prototype.sayName=function(){
console.log(this.name)
}
var liu=new Person("liuyushu",18); //实例化对象
console.log(liu.name) //liuyushu
liu.sayName() //liuyushu
</script>
/* 构造函数:就是构造一个对象的函数 */
/* 使用new关键字去实例化对象 */
/* 在构造函数中 谁使用new关键字调用构造函数,this就指向谁 */
2.原型
原型对象的作用,就是定义所有实例化对象共享的属性和方法
<script>
/* 只要在类的原型上设置了一个方法,那么所有的对象都拥有了这个方法 */
/* Array
push
Array.prototype.push
写在原型上
sayHello
*/
var arr = new Array(1,2,3);
Array.prototype.sayHello = function(){
console.log("hello")
}
var a = [4,5,6]
arr.push(4)
arr.sayHello()
a.sayHello()
</script>