经典闭包实例化,原型创建与继承
function vie(){ var speed = 100 return { getSpeed: () => speed, speedUp:function(){ speed+=10 } } } console.log(vie().getSpeed()) vie().speedUp() console.log(vie().getSpeed()) var car = vie() car.speedUp() car.speedUp() console.log(car.getSpeed())
原型创建与继承
function Viechel() { this.speed = 100; } Viechel.prototype.speedUp = function() { this.speed += 10; } var car = new Viechel();
1.为什么不在原型里面写function?
每一个实例对象,type
属性和eat()
方法都是一模一样的内容,每一次生成一个实例,都必须为重复的内容,多占用一些内存。这样既不环保,也缺乏效率,调用原型的prototype方法,是调用同一个内存地址
function Cat(name, color) { this.name = name; this.color = color; this.type = "猫科动物"; this.eat = function () { console.log(this.name); }; this.o = function () { console.log(this.color); }; } Cat.prototype.p = function () { console.log(this.color); }; var cat1 = new Cat("大毛", "黄色"); var cat2 = new Cat("二毛", "黑色"); console.log(cat1.eat == cat2.eat) // false console.log(cat1.p == cat2.p) // true
// 1.工厂模式
function createPerson(name, age, job) { var o = new Object(); o.name = name; o.age = age; o.job = job; o.sayName = function () { console.log(this.name); }; return o; } var person1 = createPerson("Nicholas", 29, "Software Engineer"); var person2 = createPerson("Greg", 27, "Doctor"); person1.sayName() person2.sayName()
// 构造函数模式
function Person(name, age, job) { this.name = name; this.age = age; this.job = job; this.sayName = function () { console.log(this.name); }; } var person3 = new Person("Nicholas", 29, "Software Engineer"); var person4 = new Person("Greg", 27, "Doctor"); person3.sayName() person4.sayName()
//原型模式
function Person() {} Person.prototype.name = "Nicholas"; Person.prototype.age = 29; Person.prototype.job = "Software Engineer"; Person.prototype.sayName = function () { console.log(this.name); }; var person1 = new Person(); person1.sayName(); //"Nicholas" var person2 = new Person(); person2.sayName(); //"Nicholas" alert(person1.sayName == person2.sayName);
//原型模式和构造函数模式组合
function Person(name, age, job) { this.name = name; this.age = age; this.job = job; this.friends = ["Shelby", "Court"]; } Person.prototype = { constructor: Person, sayName: function () { alert(this.name); } } var person1 = new Person("Nicholas", 29, "Software Engineer"); var person2 = new Person("Greg", 27, "Doctor"); person1.friends.push("Van"); alert(person1.friends); //"Shelby,Count,Van" alert(person2.friends); //"Shelby,Count" alert(person1.friends === person2.friends); //false alert(person1.sayName === person2.sayName); //true