首页 > 试题广场 >

执行以下程序,输出结果为() function Person

[单选题]

执行以下程序,输出结果为()

function Person(age){

       this.age = age;

 }

Person.prototype = {

       constructor:Person,

       getAge:function(){

            console.log(this.age);

        },

 }

var ldh = new Person(24);

Person.prototype.age = 18;

Object.prototype.age = 20;

ldh.getAge();

  • 24
  • 18 
  • 20
  • undefined
function Person(age) {
    this.age = age;
}
Person.prototype = {
    constructor: Person,
    getAge: function () {
        console.log(this.age);
    },
}
var ldh = new Person(24);  //ldh = { age: 24 }
Person.prototype.age = 18; 
// Person.prototype = { 
//                   age: 18 ,
//                   getAge: function () {
//                        console.log(this.age);
//                   },
//}
Object.prototype.age = 20; // Object.prototype = { age: 20 }
ldh.getAge(); //ldh这个对象上没有getAge方法,就去构造函数的原型上找
              //继承构造函数的原型上的getAge这个方法,this指向的是实例化对象ldh

发表于 2022-01-20 13:56:16 回复(0)
很简单,一层一层往上找,如果本地有那就不会往上找了。
发表于 2021-12-11 08:26:40 回复(0)
new Person实例赋值给变量ldh,此时this指向window,在window对象中新建了变量age,而调用getAge时,this指向调用者ldh,也是指向window,所以打印出来的是window对象里的age
发表于 2021-12-22 01:24:16 回复(1)
我理解考的是this的指向,谁调用原型,this就指向哪个实例,实例中的age就是24,不受原型和object原型的age值影响
发表于 2023-03-09 08:48:13 回复(0)