let obj = {
name: 'zhang',
age: 12,
sayName: function () {console.log(this.name);
}
}
console.log(obj);//{name: 'zhang', age: 12, sayName: [Function: sayName] }
function Person() {}
// 定义一个 function,如果应用 new"实例化", 该 function 能够看作是一个 Class
let person = new Person()
// 给 person 对象实例增加属性
person.name = 'zhang'
person.age = 13
person.sayName = function () {console.log(this.age);
}
console.log(person);//Person {name: 'zhang', age: 13, sayName: [Function (anonymous)] }
function Dog(name, age, color) {
this.name = name
this.age = age
this.color = color
this.sayName = function () {console.log(this.name);
}
}
let dog1 = new Dog('luky', 2, 'yellow')
console.log(dog1); //Dog {name: 'luky',age: 2,color: 'yellow',sayName: [Function (anonymous)] }
dog1.sayName() //luky
// 增加到全局对象 在 node 环境中全局对象是 global,在浏览器执行环境中,全局对象是 window
Dog('lily', 3, 'black')
global.sayName() //lily
//window.sayName() //lily // 在浏览器中执行才会有输入后果
// call 指针的实现示例:// 在另一个对象的作用域中调用
// 新建一个对象
let objCall = new Object()
Dog.call(obj, '小七', 2, 'gold')
obj.sayName() // 小七
console.log(obj.color); //gold
function createPerson(name, age, gender) {let person = new Object()
// 给 person 实例增加属性
person.name = name
person.age = age
person.gender = gender
person.sayName = function () {console.log(this.name);
}
return person
}
let person1 = createPerson('zhang', 18, 'male')
console.log(person1); // {name: 'zhang', age: 18, gender: 'male', sayName: [Function (anonymous)] }
person1.sayName() //zhang
// 构造函数中放公有属性和办法
function Pig(name, age, hobby) {
this.name = name
this.age = age
this.hobby = hobby
this.friends = ['六尾','德华']
}
// 在原型对象中寄存私有属性和办法 Person.prototype 重写后指向 Object,不指向原来的 Person
Person.prototype = {
// 让 constructor 属性从新指向 Person
constructor: Pig,
sayName: function () {console.log(this.name);
}
}
// 创建对象实例
let p1 = new Pig('小香', 1, '苹果')
let p2 = new Pig('小芳', 3, '炸鸡');
console.log(p1); //Pig {name: '小香', age: 1, hobby: '苹果', friends: [ '六尾', '德华'] }
// 扭转其中一个实例
p1.friends.push('robin');
// 实例之间的公有属性互不影响
console.log(p1.friends);//['六尾', '德华', 'robin']
console.log(p2.friends);//['六尾', '德华']