目录
- 定义:属性加上方法。
var animal={
name:"animal",
sex:function(){
console.log("2");
}
}
animal.sex();
animal.age="11";//给对象增加属性
- 2.对象中继承问题 关键字__proto__
var cat = {
name:"小猫猫",
__proto__:animal//继承animal对象
}
var dog ={
dog:"小狗狗",
__proto__:animal //继承
}
- 3构造函数(为了像java靠拢)
function Student(name){
this.name = name;
this.sayHello = function(){
console.log("我是"+this.name);
}
}
zhangsan = new Student("张三");
zhangsan.sayhello();//输出:我是张三
1.4由于每个新建的对象都会有一个sayHello这个方法,所以会造成资源浪费,衍生出一下写法
function Student(name){
this.name = name,
}
student.prototype={
sayHello = function(){
console.log("我是"+this.name);
}
var zhangsan = new Student("张三");
var lisi = new Student("李四"); //李四未调用sayHello方法
zhangsan.sayHello();//张三调用了sayHello方法
- 5由于以上写法中__proto__和prototype容易让人混淆,所以出了语法糖,其结构如下
class Student{
constructor(name) = {
this.name = name;
}
sayHello = function(){
console.log("我是"+this.name);
}
}
var zhangsan = new Student(name);
zhangsan.sayhello;