美文网首页
javascript 对象---原型与原型链

javascript 对象---原型与原型链

作者: 交大小丑 | 来源:发表于2018-04-20 17:33 被阅读0次

原型prototype

  1. 原型的定义: 原型是function对象的一个属性,它定义了构造函数制造出的对象的公共祖先。通过改构造函数产生的对象,可以继承该原型的属性和方法。原型也是对象。
  2. 利用原型特点和概念,可以提取共有属性。将一类对象的共有属性提取出来,放到该类对象的原型中,从而不需要每次用new操作符时都重新定义一遍该共有属性。

如下,定义一个Person构造函数,而属于Person多构造对象共有的属性方法,则定义到Person的原型中

Person.prototype = {
       eat: function (food) {
          console.log('I have eated ' + food);
       },
       sleep: function () {
         console.log("I am sleeping");
       }
}
// 人的构造函数
function Person (name, age) {
       this.name = name;
       this.age = age;
}
var person1 = new Person('lyl', 18);
console.log(person1.name); //lyl
person1.eat('apple'); //I have eated apple
只有构造函数
// 人的构造函数
function Person(name, age) {
   this.name = name;
   this.age = age;
}
console.log(Person.__proto__); //function ()
console.log(Person.prototype);  // Object { … }
console.log(Person.constructor); // function Function()
console.log(Person.constructor.prototype); // function ()
有构造函数和原型
// 人的原型
Person.prototype = {
           eat: function(food) {
               console.log('I have eated ' + food);
           },
           sleep: function() {
               console.log("I am sleeping");
           }
}
// 人的构造函数
function Person(name, age) {
       
   this.name = name;
   this.age = age;
}       
console.log(Person.__proto__); //function ()
console.log(Person.prototype);  // Object { eat: eat(), sleep: sleep() }
console.log(Person.constructor); // function Function()
console.log(Person.constructor.prototype); // function ()

参考

https://blog.csdn.net/CherishLyf/article/details/50517425

相关文章

网友评论

      本文标题:javascript 对象---原型与原型链

      本文链接:https://www.haomeiwen.com/subject/ysdzkftx.html