gpt4 book ai didi

javascript 原型(prototype)链对象 vs 函数对象

转载 作者:行者123 更新时间:2023-11-30 09:25:29 26 4
gpt4 key购买 nike

<分区>

我可能没有正确制作标题,但请有人解释为什么我不能为人物对象创建原型(prototype)?只有当我点击 Object.prototype 链时才有效。

const person = {
isHuman: false,
printIntroduction: function () {
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
}
};

//person.prototype.hit = function(){
// console.log("hitting me");
//}

Object.prototype.hit = function(){
console.log("hitting me");
}

const me = Object.create(person);

me.name = "Matthew"; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // inherited properties can be overwritten

me.printIntroduction();
me.hit();

(更新)。为什么这有效?不确定此示例实际上有什么区别,但此代码有效。

function person {
isHuman: false,
printIntroduction: function () {
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
}
}();

person.prototype.hit = function(){

console.log("hitting me");
}

/*
person.prototype.hit = function(){
console.log("hitting me");
}
*/

Object.prototype.hit = function(){
console.log("hitting me");
}

const me = Object.create(person);

me.name = "Matthew"; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // inherited properties can be overwritten

me.printIntroduction();
me.hit();
// expected output: "My name is Matthew. Am I human? true"

更新2

好的,所以我让它像下面那样工作,但显然原型(prototype)没有按我预期的方式工作..所以我显然对原型(prototype)感到困惑

function person(){
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
}

person.prototype.hit = function(){
console.log("hitting me1");
}

Object.prototype.hit = function(){
console.log("hitting me2");
}

const me = Object.create(person);

me.hit();

更新 3.

谢谢..这是我从下面得到的解释..谢谢,现在很清楚了。

function person(){
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
}

person.prototype.hit = function(){
console.log("hitting me1");
}

Object.prototype.hit = function(){
console.log("hitting me2");
}

//const me = Object.create(person);
const me = new person;

me.hit();

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com