原型(prototype)
1.1访问原型的方法
function human () {} human.prototype.name = "people" human.prototype.sayname = function(){console.log(this.name);} var jack = new human console.log(human.prototype) //{ name: ‘people‘, sayname: [Function] } console.log(jack.__proto__) //{ name: ‘people‘, sayname: [Function] } console.log(Object.getPrototypeOf(jack)) //{ name: ‘people‘, sayname: [Function] }
前两种方法都能修改原型,最后一种只能访问。
创建对象
1.1使用构造函数问题
function Person(name, age, job){ this.name = name; this.age = age; this.job = job; this.sayName = function(){ console.log(this.name); }; } var person1 = new Person var person2 = new Person console.log(person1.sayName == person2.sayName); //false
每次实例化一个对象,构造函数中的方法就重新创建一遍。
1.2原型模式的缺点
function Person(){ } Person.prototype = { constructor: Person, name : "Nicholas", age : 29, job : "Software Engineer", friends : ["Shelby", "Court"], sayName : function () { alert(this.name); } }; var person1 = new Person(); var person2 = new Person(); person1.friends.push("Van"); alert(person1.friends); //"Shelby,Court,Van" alert(person2.friends); //"Shelby,Court,Van" alert(person1.friends === person2.friends); //true
原型模式通过原型共享属性和方法,但是也是这样引出了问题。person1.friends和person2.friends都是指向原型中friends的引用,所以当有一个实例修改friends后,其他的实例也会一起改变。
1.3常用创建对象方法(构造函数模式与原型模式的组合使用)
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,Court,Van" alert(person2.friends); //"Shelby,Court" alert(person1.friends === person2.friends); //false alert(person1.sayName === person2.sayName); //true
构造函数模式创建属性,原型模式创建方法
继承的基本原理-原型链
function human (jobName) { this.jobName = jobName } human.prototype.sayjobName = function(){console.log(this.jobName);} function student (learn){} student.prototype = new human("student") student.prototype.learn = function(learn){ console.log(learn); }; jack = new student("jack") console.log(jack.learn("math")); //math console.log(jack.jobName); //student console.log(jack.sayjobName()); //student console.log(jack.__proto__); //{ jobName: ‘student‘, learn: [Function] } console.log(jack.__proto__.__proto__); //{ sayjobName: [Function] }
student继承与human有其jobName属性和sayjobName方法。通过对student原型内利用创建一个human实例的方法,添加了一个指向human原型的引用。
时间: 2024-10-23 00:06:04