隐式原型(对象内使用)
var animal={
name:"zengyu",
eat:function(){
console.log( `${this.name} is eatting`);
}
}
var cat ={
name:"cat",
__proto__:animal
}
var dog={
name:"dog",
__proto__:animal
}
animal.eat();
cat.eat();
dog.eat();
js中可以通过__proto__实现继承,类似于extends。
也就是说,实例对象可以通过其__proto__指向到原型对象

而通过不断地proto属性,就会达成一个原型链,是不是很简单。
可是还没完。。。。
显式原型
初探:构造函数
function Student(name){
this.name=name;
this.sayHello=function(){
console.log(`${this.name} is saying hello`);
}
}
var ershizi= new Student("二傻子");
var maoge=new Student("冒哥");
ershizi.sayHello();
maoge.sayHello();
JavaScript 中的所有数据都能以对象的形式表现:由于函数是对象,也就是说,我们可以new 一个Student函数,传递给对象,

二探:显式原型
而在上面的代码中,每个对象都会有一个sayhello函数,那有什么办法可以减少使用呢。这时,我们可以把sayHello这个方法提取出来,怎么提取,通过原型
function Student(name){
this.name=name;
// this.sayHello=function(){
// console.log(`${this.name} is saying hello`);
// }
}
Student.prototype={
sayHello:function(){
console.log(`${this.name} is saying hello`);
}
}
var ershizi= new Student("二傻子");
var maoge=new Student("冒哥");
ershizi.sayHello();
console.log(maoge);
此时,每个新建的对象,都会在自己的__proto__属性中指向到所指的原型对象。
可以看以下代码:

也就是说,构造函数可以通过prototype 指向原型对象

js的语法糖–constructor
class Student{
constructor(name)
{
this.name=name;
}
sayHello()
{
console.log(`${this.name} is saying hello`);
}
}
var ershazi= new Student("二傻子");
ershazi.sayHello();
看到没,看到没。
js中,任一原型对象可以通过constructor函数,来指定对应的构造函数,也就是说

值得一提的时,一个原型对象只能有一个构造函数,即只能有一个constructor修饰
本文深入解析JavaScript中的隐式原型和显式原型概念,探讨对象如何通过__proto__属性实现继承,以及构造函数如何通过prototype属性指向原型对象。同时,介绍了如何利用原型减少代码重复,并通过class语法糖进一步简化原型和构造函数的使用。
302

被折叠的 条评论
为什么被折叠?



