javascript自己对原型的浅入理解

原型的定义:原型式function对象的一个属性,它定义了构造函数制造出的对象的公共祖先。通过该构造函数产生的对象,可以继承该原型的属性和方法。原型也是对象。
原型的几个小知识:
1…利用原型特点和概念,可以提取共有属性。
2.对象如何查看原型 ———>隐式属性 proto
3.对象如何查看对象的构造函数 ——>constructor
4.在原型里面 Person.prototype --原型 Person.prototype = {} 是祖先

代码如下:

<script>
Person.prototype.LastName = 'xw' //是公有祖先
Person.prototype.say = function(){
console.log('pig')
}
function Person(){
this.name = 'jj'
}
var person = new Person();
console.log(person.LastName)//xw
person.say()//pig
console.log(person.name)//jj
var person1 = new Person();
console.log(person1.LastName)//xw
person1.say()//pig
console.log(person1.name)//jj
function Person(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
var person = new Person('zhou',19,'woman')
console.log(person)//Person {name: "zhou", age: 19, sex: "woman"}
function Car(color,owner){
this.color = color;
this.carName = 'BMW';
this.height = 1400;
this.lang = 4900;
this.owner = owner
}
var car = new Car('red','xw')
console.log(car)//Car {color: "red", carName: "BMW", height: 1400, lang: 4900, owner: "xw"}
Car.prototype.height = 1400;
Car.prototype.carName = 'BMW';
Car.prototype.lang = 4900;
function Car(color,owner){
this.color = color;
this.owner = owner
}
var car1 = new Car('biue','zhou')
console.log(car1)
// car1.height = 1400
Person.prototype.LastName = 'xw'
function Person(name) {
this.name = name;
}
var person = new Person('zhou');
Person.prototype.LastName = 'qwe';
</script>

猜你喜欢

转载自blog.csdn.net/weixin_44260238/article/details/88357250
今日推荐